// URL: /article/new // 新建文章 func newArticleHandler(w http.ResponseWriter, r *http.Request) { var categories []ArticleCategory c := DB.C("articlecategories") c.Find(nil).All(&categories) var choices []wtforms.Choice for _, category := range categories { choices = append(choices, wtforms.Choice{Value: category.Id_.Hex(), Label: category.Name}) } form := wtforms.NewForm( wtforms.NewHiddenField("html", ""), wtforms.NewTextField("title", "标题", "", wtforms.Required{}), wtforms.NewTextField("original_source", "原始出处", "", wtforms.Required{}), wtforms.NewTextField("original_url", "原始链接", "", wtforms.URL{}), wtforms.NewSelectField("category", "分类", choices, ""), ) if r.Method == "POST" && form.Validate(r) { user, _ := currentUser(r) c = DB.C("contents") id_ := bson.NewObjectId() html := form.Value("html") html = strings.Replace(html, "<pre>", `<pre class="prettyprint linenums">`, -1) categoryId := bson.ObjectIdHex(form.Value("category")) err := c.Insert(&Article{ Content: Content{ Id_: id_, Type: TypeArticle, Title: form.Value("title"), CreatedBy: user.Id_, CreatedAt: time.Now(), }, Id_: id_, CategoryId: categoryId, OriginalSource: form.Value("original_source"), OriginalUrl: form.Value("original_url"), }) if err != nil { fmt.Println("newArticleHandler:", err.Error()) return } http.Redirect(w, r, "/a/"+id_.Hex(), http.StatusFound) return } renderTemplate(w, r, "article/form.html", map[string]interface{}{ "form": form, "title": "新建", "action": "/article/new", "active": "article", }) }
// URL: /package/new // 新建第三方包 func newPackageHandler(handler *Handler) { user, _ := currentUser(handler) var categories []PackageCategory c := handler.DB.C(PACKAGE_CATEGORIES) c.Find(nil).All(&categories) var choices []wtforms.Choice for _, category := range categories { choices = append(choices, wtforms.Choice{Value: category.Id_.Hex(), Label: category.Name}) } form := wtforms.NewForm( wtforms.NewHiddenField("html", ""), wtforms.NewTextField("name", "名称", "", wtforms.Required{}), wtforms.NewSelectField("category_id", "分类", choices, ""), wtforms.NewTextField("url", "网址", "", wtforms.Required{}, wtforms.URL{}), wtforms.NewTextArea("description", "描述", "", wtforms.Required{}), ) if handler.Request.Method == "POST" && form.Validate(handler.Request) { c = handler.DB.C(CONTENTS) id := bson.NewObjectId() categoryId := bson.ObjectIdHex(form.Value("category_id")) html := form.Value("html") html = strings.Replace(html, "<pre>", `<pre class="prettyprint linenums">`, -1) c.Insert(&Package{ Content: Content{ Id_: id, Type: TypePackage, Title: form.Value("name"), Markdown: form.Value("description"), Html: template.HTML(html), CreatedBy: user.Id_, CreatedAt: time.Now(), }, Id_: id, CategoryId: categoryId, Url: form.Value("url"), }) c = handler.DB.C(PACKAGE_CATEGORIES) // 增加数量 c.Update(bson.M{"_id": categoryId}, bson.M{"$inc": bson.M{"packagecount": 1}}) http.Redirect(handler.ResponseWriter, handler.Request, "/p/"+id.Hex(), http.StatusFound) return } handler.renderTemplate("package/form.html", BASE, map[string]interface{}{ "form": form, "title": "提交第三方包", "action": "/package/new", "active": "package", }) }
// URL: /signin // 处理用户登录,如果登录成功,设置Cookie func signinHandler(w http.ResponseWriter, r *http.Request) { next := r.FormValue("next") form := wtforms.NewForm( wtforms.NewHiddenField("next", next), wtforms.NewTextField("username", "用户名", "", &wtforms.Required{}), wtforms.NewPasswordField("password", "密码", &wtforms.Required{}), ) if r.Method == "POST" { if form.Validate(r) { c := DB.C("users") user := User{} err := c.Find(bson.M{"username": form.Value("username")}).One(&user) if err != nil { form.AddError("username", "该用户不存在") renderTemplate(w, r, "account/signin.html", map[string]interface{}{"form": form}) return } if !user.IsActive { form.AddError("username", "邮箱没有经过验证,如果没有收到邮件,请联系管理员") renderTemplate(w, r, "account/signin.html", map[string]interface{}{"form": form}) return } if user.Password != encryptPassword(form.Value("password")) { form.AddError("password", "密码和用户名不匹配") renderTemplate(w, r, "account/signin.html", map[string]interface{}{"form": form}) return } session, _ := store.Get(r, "user") session.Values["username"] = user.Username session.Save(r, w) if form.Value("next") == "" { http.Redirect(w, r, "/", http.StatusFound) } else { http.Redirect(w, r, next, http.StatusFound) } return } } renderTemplate(w, r, "account/signin.html", map[string]interface{}{"form": form}) }
// URL: /topic/new // 新建主题 func newTopicHandler(w http.ResponseWriter, r *http.Request) { nodeId := mux.Vars(r)["node"] var nodes []Node c := DB.C("nodes") c.Find(nil).All(&nodes) var choices = []wtforms.Choice{wtforms.Choice{}} // 第一个选项为空 for _, node := range nodes { choices = append(choices, wtforms.Choice{Value: node.Id_.Hex(), Label: node.Name}) } form := wtforms.NewForm( wtforms.NewHiddenField("html", ""), wtforms.NewSelectField("node", "节点", choices, nodeId, &wtforms.Required{}), wtforms.NewTextArea("title", "标题", "", &wtforms.Required{}), wtforms.NewTextArea("content", "内容", ""), ) var content string var html template.HTML if r.Method == "POST" { if form.Validate(r) { session, _ := store.Get(r, "user") username, _ := session.Values["username"] username = username.(string) user := User{} c = DB.C("users") c.Find(bson.M{"username": username}).One(&user) c = DB.C("contents") id_ := bson.NewObjectId() now := time.Now() html2 := form.Value("html") html2 = strings.Replace(html2, "<pre>", `<pre class="prettyprint linenums">`, -1) nodeId := bson.ObjectIdHex(form.Value("node")) err := c.Insert(&Topic{ Content: Content{ Id_: id_, Type: TypeTopic, Title: form.Value("title"), Markdown: form.Value("content"), Html: template.HTML(html2), CreatedBy: user.Id_, CreatedAt: now, }, Id_: id_, NodeId: nodeId, LatestRepliedAt: now, }) if err != nil { fmt.Println("newTopicHandler:", err.Error()) return } // 增加Node.TopicCount c = DB.C("nodes") c.Update(bson.M{"_id": nodeId}, bson.M{"$inc": bson.M{"topiccount": 1}}) c = DB.C("status") var status Status c.Find(nil).One(&status) c.Update(bson.M{"_id": status.Id_}, bson.M{"$inc": bson.M{"topiccount": 1}}) http.Redirect(w, r, "/t/"+id_.Hex(), http.StatusFound) return } content = form.Value("content") html = template.HTML(form.Value("html")) form.SetValue("html", "") } renderTemplate(w, r, "topic/form.html", map[string]interface{}{ "form": form, "title": "新建", "html": html, "content": content, "action": "/topic/new", "active": "topic", }) }
// URL: /t/{topicId}/edit // 编辑主题 func editTopicHandler(w http.ResponseWriter, r *http.Request) { user, _ := currentUser(r) topicId := mux.Vars(r)["topicId"] c := DB.C("contents") var topic Topic err := c.Find(bson.M{"_id": bson.ObjectIdHex(topicId), "content.type": TypeTopic}).One(&topic) if err != nil { message(w, r, "没有该主题", "没有该主题,不能编辑", "error") return } if !topic.CanEdit(user.Username) { message(w, r, "没有该权限", "对不起,你没有权限编辑该主题", "error") return } var nodes []Node c = DB.C("nodes") c.Find(nil).All(&nodes) var choices = []wtforms.Choice{wtforms.Choice{}} // 第一个选项为空 for _, node := range nodes { choices = append(choices, wtforms.Choice{Value: node.Id_.Hex(), Label: node.Name}) } form := wtforms.NewForm( wtforms.NewHiddenField("html", ""), wtforms.NewSelectField("node", "节点", choices, topic.NodeId.Hex(), &wtforms.Required{}), wtforms.NewTextArea("title", "标题", topic.Title, &wtforms.Required{}), wtforms.NewTextArea("content", "内容", topic.Markdown), ) content := topic.Markdown html := topic.Html if r.Method == "POST" { if form.Validate(r) { html2 := form.Value("html") html2 = strings.Replace(html2, "<pre>", `<pre class="prettyprint linenums">`, -1) nodeId := bson.ObjectIdHex(form.Value("node")) c = DB.C("contents") c.Update(bson.M{"_id": topic.Id_}, bson.M{"$set": bson.M{ "nodeid": nodeId, "content.title": form.Value("title"), "content.markdown": form.Value("content"), "content.html": template.HTML(html2), "content.updatedat": time.Now(), "content.updatedby": user.Id_.Hex(), }}) // 如果两次的节点不同,更新节点的主题数量 if topic.NodeId != nodeId { c = DB.C("nodes") c.Update(bson.M{"_id": topic.NodeId}, bson.M{"$inc": bson.M{"topiccount": -1}}) c.Update(bson.M{"_id": nodeId}, bson.M{"$inc": bson.M{"topiccount": 1}}) } http.Redirect(w, r, "/t/"+topic.Id_.Hex(), http.StatusFound) return } content = form.Value("content") html = template.HTML(form.Value("html")) form.SetValue("html", "") } renderTemplate(w, r, "topic/form.html", map[string]interface{}{ "form": form, "title": "编辑", "action": "/t/" + topicId + "/edit", "html": html, "content": content, "active": "topic", }) }
// URL: /package/{packageId}/edit // 编辑第三方包 func editPackageHandler(handler *Handler) { user, _ := currentUser(handler) vars := mux.Vars(handler.Request) packageId := vars["packageId"] if !bson.IsObjectIdHex(packageId) { http.NotFound(handler.ResponseWriter, handler.Request) return } package_ := Package{} c := handler.DB.C(CONTENTS) err := c.Find(bson.M{"_id": bson.ObjectIdHex(packageId), "content.type": TypePackage}).One(&package_) if err != nil { message(handler, "没有该包", "没有该包", "error") return } if !package_.CanEdit(user.Username, handler.DB) { message(handler, "没有权限", "你没有权限编辑该包", "error") return } var categories []PackageCategory c = handler.DB.C(PACKAGE_CATEGORIES) c.Find(nil).All(&categories) var choices []wtforms.Choice for _, category := range categories { choices = append(choices, wtforms.Choice{Value: category.Id_.Hex(), Label: category.Name}) } form := wtforms.NewForm( wtforms.NewHiddenField("html", ""), wtforms.NewTextField("name", "名称", package_.Title, wtforms.Required{}), wtforms.NewSelectField("category_id", "分类", choices, package_.CategoryId.Hex()), wtforms.NewTextField("url", "网址", package_.Url, wtforms.Required{}, wtforms.URL{}), wtforms.NewTextArea("description", "描述", package_.Markdown, wtforms.Required{}), ) if handler.Request.Method == "POST" && form.Validate(handler.Request) { c = handler.DB.C(CONTENTS) categoryId := bson.ObjectIdHex(form.Value("category_id")) html := form.Value("html") html = strings.Replace(html, "<pre>", `<pre class="prettyprint linenums">`, -1) c.Update(bson.M{"_id": package_.Id_}, bson.M{"$set": bson.M{ "categoryid": categoryId, "url": form.Value("url"), "content.title": form.Value("name"), "content.markdown": form.Value("description"), "content.html": template.HTML(html), "content.updateDBy": user.Id_.Hex(), "content.updatedat": time.Now(), }}) c = handler.DB.C(PACKAGE_CATEGORIES) if categoryId != package_.CategoryId { // 减少原来类别的包数量 c.Update(bson.M{"_id": package_.CategoryId}, bson.M{"$inc": bson.M{"packagecount": -1}}) // 增加新类别的包数量 c.Update(bson.M{"_id": categoryId}, bson.M{"$inc": bson.M{"packagecount": 1}}) } http.Redirect(handler.ResponseWriter, handler.Request, "/p/"+package_.Id_.Hex(), http.StatusFound) return } form.SetValue("html", "") handler.renderTemplate("package/form.html", BASE, map[string]interface{}{ "form": form, "title": "编辑第三方包", "action": "/p/" + packageId + "/edit", "active": "package", }) }
// URL: /signin // 处理用户登录,如果登录成功,设置Cookie func signinHandler(handler *Handler) { // 如果已经登录了,跳转到首页 _, has := currentUser(handler) if has { handler.Redirect("/") } next := handler.Request.FormValue("next") form := wtforms.NewForm( wtforms.NewHiddenField("next", next), wtforms.NewTextField("username", "用户名", "", &wtforms.Required{}), wtforms.NewPasswordField("password", "密码", &wtforms.Required{}), wtforms.NewTextField("geetest_challenge", "challenge", ""), wtforms.NewTextField("geetest_validate", "validate", ""), wtforms.NewTextField("geetest_seccode", "seccode", ""), ) geeTest := geetest.NewGeeTest(Config.GtCaptchaId, Config.GtPrivateKey) if handler.Request.Method == "POST" { if form.Validate(handler.Request) { // 检查验证码 if !geeTest.Validate(form.Value("geetest_challenge"), form.Value("geetest_validate"), form.Value("geetest_seccode")) { handler.renderTemplate("account/signin.html", BASE, map[string]interface{}{ "form": form, "captchaErr": true, }) return } c := handler.DB.C(USERS) user := User{} err := c.Find(bson.M{"username": form.Value("username")}).One(&user) if err != nil { form.AddError("username", "该用户不存在") handler.renderTemplate("account/signin.html", BASE, map[string]interface{}{ "form": form, "gtUrl": geeTest.EmbedURL(), }) return } if !user.IsActive { form.AddError("username", "邮箱没有经过验证,如果没有收到邮件,请联系管理员") handler.renderTemplate("account/signin.html", BASE, map[string]interface{}{ "form": form, "gtUrl": geeTest.EmbedURL(), }) return } if !user.CheckPassword(form.Value("password")) { form.AddError("password", "密码和用户名不匹配") handler.renderTemplate("account/signin.html", BASE, map[string]interface{}{ "form": form, "gtUrl": geeTest.EmbedURL(), }) return } session, _ := store.Get(handler.Request, "user") session.Values["username"] = user.Username session.Save(handler.Request, handler.ResponseWriter) if form.Value("next") == "" { http.Redirect(handler.ResponseWriter, handler.Request, "/", http.StatusFound) } else { http.Redirect(handler.ResponseWriter, handler.Request, next, http.StatusFound) } return } } handler.renderTemplate("account/signin.html", BASE, map[string]interface{}{ "form": form, "gtUrl": geeTest.EmbedURL(), }) }
// URL: /signin // 处理用户登录,如果登录成功,设置Cookie func signinHandler(handler *Handler) { // 如果已经登录了,跳转到首页 _, has := currentUser(handler) if has { handler.Redirect("/") } next := handler.Request.FormValue("next") form := wtforms.NewForm( wtforms.NewHiddenField("next", next), wtforms.NewTextField("username", "用户名", "", &wtforms.Required{}), wtforms.NewPasswordField("password", "密码", &wtforms.Required{}), wtforms.NewTextField("captcha", "验证码", "", wtforms.Required{}), wtforms.NewHiddenField("captchaId", ""), ) if handler.Request.Method == "POST" { if form.Validate(handler.Request) { // 检查验证码 if !captcha.VerifyString(form.Value("captchaId"), form.Value("captcha")) { form.AddError("captcha", "验证码错误") form.SetValue("captcha", "") handler.renderTemplate("account/signin.html", BASE, map[string]interface{}{"form": form, "captchaId": captcha.New()}) return } c := handler.DB.C(USERS) user := User{} err := c.Find(bson.M{"username": form.Value("username")}).One(&user) if err != nil { form.AddError("username", "该用户不存在") form.SetValue("captcha", "") handler.renderTemplate("account/signin.html", BASE, map[string]interface{}{"form": form, "captchaId": captcha.New()}) return } if !user.IsActive { form.AddError("username", "邮箱没有经过验证,如果没有收到邮件,请联系管理员") form.SetValue("captcha", "") handler.renderTemplate("account/signin.html", BASE, map[string]interface{}{"form": form, "captchaId": captcha.New()}) return } if user.Password != encryptPassword(form.Value("password"), user.Salt) { form.AddError("password", "密码和用户名不匹配") form.SetValue("captcha", "") handler.renderTemplate("account/signin.html", BASE, map[string]interface{}{"form": form, "captchaId": captcha.New()}) return } session, _ := store.Get(handler.Request, "user") session.Values["username"] = user.Username session.Save(handler.Request, handler.ResponseWriter) if form.Value("next") == "" { http.Redirect(handler.ResponseWriter, handler.Request, "/", http.StatusFound) } else { http.Redirect(handler.ResponseWriter, handler.Request, next, http.StatusFound) } return } } form.SetValue("captcha", "") handler.renderTemplate("account/signin.html", BASE, map[string]interface{}{"form": form, "captchaId": captcha.New()}) }
// URL: /signup // 处理用户注册,要求输入用户名,密码和邮箱 func signupHandler(handler *Handler) { // 如果已经登录了,跳转到首页 _, has := currentUser(handler) if has { handler.Redirect("/") } var username string var email string session, _ := store.Get(handler.Request, "user") if handler.Request.Method == "GET" { //如果是从新建关联过来的就自动填充字段 if session.Values[GITHUB_PROVIDER] == GITHUB_COM { username = session.Values[GITHUB_ID].(string) email = session.Values[GITHUB_EMAIL].(string) } } form := wtforms.NewForm( wtforms.NewTextField("username", "用户名", username, wtforms.Required{}, wtforms.Regexp{Expr: `^[a-zA-Z0-9_]{3,16}$`, Message: "请使用a-z, A-Z, 0-9以及下划线, 长度3-16之间"}), wtforms.NewPasswordField("password", "密码", wtforms.Required{}), wtforms.NewTextField("email", "电子邮件", email, wtforms.Required{}, wtforms.Email{}), wtforms.NewTextField("captcha", "验证码", "", wtforms.Required{}), wtforms.NewHiddenField("captchaId", ""), ) if handler.Request.Method == "POST" { if form.Validate(handler.Request) { // 检查验证码 if !captcha.VerifyString(form.Value("captchaId"), form.Value("captcha")) { form.AddError("captcha", "验证码错误") fmt.Println("captcha") form.SetValue("captcha", "") handler.renderTemplate("account/signup.html", BASE, map[string]interface{}{"form": form, "captchaId": captcha.New()}) return } c := handler.DB.C(USERS) result := User{} // 检查用户名 err := c.Find(bson.M{"username": form.Value("username")}).One(&result) if err == nil { form.AddError("username", "该用户名已经被注册") form.SetValue("captcha", "") handler.renderTemplate("account/signup.html", BASE, map[string]interface{}{"form": form, "captchaId": captcha.New()}) return } // 检查邮箱 err = c.Find(bson.M{"email": form.Value("email")}).One(&result) if err == nil { form.AddError("email", "电子邮件地址已经被注册") form.SetValue("captcha", "") handler.renderTemplate("account/signup.html", BASE, map[string]interface{}{"form": form, "captchaId": captcha.New()}) return } c2 := handler.DB.C(STATUS) var status Status c2.Find(nil).One(&status) id := bson.NewObjectId() username := form.Value("username") validateCode := strings.Replace(uuid.NewUUID().String(), "-", "", -1) salt := strings.Replace(uuid.NewUUID().String(), "-", "", -1) index := status.UserIndex + 1 u := &User{ Id_: id, Username: username, Password: encryptPassword(form.Value("password"), salt), Avatar: "", // defaultAvatars[rand.Intn(len(defaultAvatars))], Salt: salt, Email: form.Value("email"), ValidateCode: validateCode, IsActive: true, JoinedAt: time.Now(), Index: index, } if session.Values[GITHUB_PROVIDER] == GITHUB_COM { u.GetGithubValues(session) defer deleteGithubValues(session) } err = c.Insert(u) if err != nil { logger.Println(err) return } c2.Update(nil, bson.M{"$inc": bson.M{"userindex": 1, "usercount": 1}}) // 重新生成users.json字符串 generateUsersJson(handler.DB) // 发送邮件 /* subject := "欢迎加入Golang 中国" message2 := `欢迎加入Golang 中国。请访问下面地址激活你的帐户。 <a href="%s/activate/%s">%s/activate/%s</a> 如果你没有注册,请忽略这封邮件。 ©2012 Golang 中国` message2 = fmt.Sprintf(message2, config["host"], validateCode, config["host"], validateCode) sendMail(subject, message2, []string{form.Value("email")}) message(w, r, "注册成功", "请查看你的邮箱进行验证,如果收件箱没有,请查看垃圾邮件,如果还没有,请给[email protected]发邮件,告知你的用户名。", "success") */ // 注册成功后设成登录状态 session, _ := store.Get(handler.Request, "user") session.Values["username"] = username session.Save(handler.Request, handler.ResponseWriter) // 跳到修改用户信息页面 http.Redirect(handler.ResponseWriter, handler.Request, "/profile", http.StatusFound) return } } form.SetValue("captcha", "") handler.renderTemplate("account/signup.html", BASE, map[string]interface{}{"form": form, "captchaId": captcha.New()}) }
// URL: /a/{articleId}/edit // 编辑主题 func editArticleHandler(w http.ResponseWriter, r *http.Request) { user, _ := currentUser(r) articleId := mux.Vars(r)["articleId"] c := DB.C("contents") var article Article err := c.Find(bson.M{"_id": bson.ObjectIdHex(articleId)}).One(&article) if err != nil { message(w, r, "没有该文章", "没有该文章,不能编辑", "error") return } if !article.CanEdit(user.Username) { message(w, r, "没用该权限", "对不起,你没有权限编辑该文章", "error") return } var categorys []ArticleCategory c = DB.C("articlecategories") c.Find(nil).All(&categorys) var choices []wtforms.Choice for _, category := range categorys { choices = append(choices, wtforms.Choice{Value: category.Id_.Hex(), Label: category.Name}) } form := wtforms.NewForm( wtforms.NewHiddenField("html", ""), wtforms.NewTextField("title", "标题", article.Title, wtforms.Required{}), wtforms.NewTextField("original_source", "原始出处", article.OriginalSource, wtforms.Required{}), wtforms.NewTextField("original_url", "原始链接", article.OriginalUrl, wtforms.URL{}), wtforms.NewSelectField("category", "分类", choices, article.CategoryId.Hex()), ) if r.Method == "POST" { if form.Validate(r) { categoryId := bson.ObjectIdHex(form.Value("category")) c = DB.C("contents") err = c.Update(bson.M{"_id": article.Id_}, bson.M{"$set": bson.M{ "categoryid": categoryId, "originalsource": form.Value("original_source"), "originalurl": form.Value("original_url"), "content.title": form.Value("title"), "content.updatedby": user.Id_.Hex(), "content.updatedat": time.Now(), }}) if err != nil { fmt.Println("update error:", err.Error()) return } http.Redirect(w, r, "/a/"+article.Id_.Hex(), http.StatusFound) return } } renderTemplate(w, r, "article/form.html", map[string]interface{}{ "form": form, "title": "编辑", "action": "/a/" + articleId + "/edit", "active": "article", }) }
// URL: /signup // 处理用户注册,要求输入用户名,密码和邮箱 func signupHandler(handler *Handler) { // 如果已经登录了,跳转到首页 _, has := currentUser(handler) if has { handler.Redirect("/") } var username string var email string session, _ := store.Get(handler.Request, "user") if handler.Request.Method == "GET" { //如果是从新建关联过来的就自动填充字段 if session.Values[GITHUB_PROVIDER] == GITHUB_COM { username = session.Values[GITHUB_ID].(string) email = session.Values[GITHUB_EMAIL].(string) } } form := wtforms.NewForm( wtforms.NewTextField("username", "用户名", username, wtforms.Required{}, wtforms.Regexp{Expr: `^[a-zA-Z0-9_]{3,16}$`, Message: "请使用a-z, A-Z, 0-9以及下划线, 长度3-16之间"}), wtforms.NewPasswordField("password", "密码", wtforms.Required{}), wtforms.NewTextField("email", "电子邮件", email, wtforms.Required{}, wtforms.Email{}), wtforms.NewTextField("captcha", "验证码", "", wtforms.Required{}), wtforms.NewHiddenField("captchaId", ""), ) if handler.Request.Method == "POST" { if form.Validate(handler.Request) { // 检查验证码 if !captcha.VerifyString(form.Value("captchaId"), form.Value("captcha")) { form.AddError("captcha", "验证码错误") fmt.Println("captcha") form.SetValue("captcha", "") handler.renderTemplate("account/signup.html", BASE, map[string]interface{}{"form": form, "captchaId": captcha.New()}) return } c := handler.DB.C(USERS) result := User{} // 检查用户名 err := c.Find(bson.M{"username": form.Value("username")}).One(&result) if err == nil { form.AddError("username", "该用户名已经被注册") form.SetValue("captcha", "") handler.renderTemplate("account/signup.html", BASE, map[string]interface{}{"form": form, "captchaId": captcha.New()}) return } // 检查邮箱 err = c.Find(bson.M{"email": form.Value("email")}).One(&result) if err == nil { form.AddError("email", "电子邮件地址已经被注册") form.SetValue("captcha", "") handler.renderTemplate("account/signup.html", BASE, map[string]interface{}{"form": form, "captchaId": captcha.New()}) return } c2 := handler.DB.C(STATUS) var status Status c2.Find(nil).One(&status) id := bson.NewObjectId() username := form.Value("username") validateCode := strings.Replace(uuid.NewUUID().String(), "-", "", -1) index := status.UserIndex + 1 u := &User{ Id_: id, Username: username, Password: GenPwd(form.Value("password")), Avatar: "", // defaultAvatars[rand.Intn(len(defaultAvatars))], Email: form.Value("email"), ValidateCode: validateCode, IsActive: true, JoinedAt: time.Now(), Index: index, } if session.Values[GITHUB_PROVIDER] == GITHUB_COM { u.GetGithubValues(session) defer deleteGithubValues(session) } err = c.Insert(u) if err != nil { logger.Println(err) return } c2.Update(nil, bson.M{"$inc": bson.M{"userindex": 1, "usercount": 1}}) // 重新生成users.json字符串 generateUsersJson(handler.DB) // 注册成功后设成登录状态 session, _ := store.Get(handler.Request, "user") session.Values["username"] = username session.Save(handler.Request, handler.ResponseWriter) // 跳到修改用户信息页面 handler.redirect("/setting/edit_info", http.StatusFound) return } } form.SetValue("captcha", "") handler.renderTemplate("account/signup.html", BASE, map[string]interface{}{"form": form, "captchaId": captcha.New()}) }