func showForm(wr *web.Context) (captid *CaptchaId) { // Patch until set another secure cookie works again // Generate its id as string captitle := captcha.New() // Generate captcha image removing previous dir, err := ioutil.ReadDir("static/images/captchas") if err == nil { for i := range dir { os.Remove("static/images/captchas/" + dir[i].Name()) } } captbyte := gen("static/images/captchas/" + captitle + "-.png") //captbyte = gen("static/images/captchas/" + captid.CaptId + "-.png") //wr.SetSecureCookie("captstr", captbyte, 20000) // Adding captcha sequence as string to struct captid = &CaptchaId{ CaptId: captitle, CaptByte: captbyte, } log.Println("DEBUG Captcha: Created new captcha ", captid.CaptId) return captid }
// generate a new captcha func (cs *CaptchaServer) NewCaptcha(w http.ResponseWriter, r *http.Request) { // obtain session sess, err := cs.store.Get(r, cs.sessionName) if err != nil { // failed to obtain session http.Error(w, err.Error(), http.StatusInternalServerError) return } // new captcha id := captcha.New() // do we want to interpret as json? use_json := r.URL.Query().Get("t") == "json" // image url url := fmt.Sprintf("%simg/%s.png", cs.prefix, id) if use_json { // send json enc := json.NewEncoder(w) enc.Encode(map[string]string{"id": id, "url": url}) } else { // set captcha id sess.Values["captcha_id"] = id // save session sess.Save(r, w) // rediect to image http.Redirect(w, r, url, http.StatusFound) } }
// create a new captcha, return as json object func (self httpFrontend) new_captcha_json(wr http.ResponseWriter, r *http.Request) { captcha_id := captcha.New() resp := make(map[string]string) // the captcha id resp["id"] = captcha_id // url of the image resp["url"] = fmt.Sprintf("%s%s.png", self.prefix, captcha_id) enc := json.NewEncoder(wr) enc.Encode(resp) }
func NewCaptcha(db *periwinkle.Tx) *Captcha { o := Captcha{ ID: captcha.New(), Value: string(captcha.RandomDigits(defaultLen)), } if err := db.Create(&o).Error; err != nil { dbError(err) } return &o }
// New creates a new capcha and returns the ID func New() Captcha { d := struct { id string }{ captcha.New(), } return Captcha{ id: d.id, } }
func captchaServer(w http.ResponseWriter, req *http.Request) { if req.Method == "GET" { w.Header().Set("Content-Type", "text/html; charset=utf-8") fmt.Fprintf(w, "%s", captcha.New()) return } else if req.Method == "POST" { if captcha.VerifyString(req.FormValue("captchaId"), req.FormValue("captchaSolution")) { } else { } } }
func newCaptcha(writer http.ResponseWriter, request *http.Request) { clientId := request.URL.Query().Get("clientId") privateKey := userStore.Get(clientId, false) if privateKey == "" { writer.WriteHeader(401) return } captchaId := captcha.New() validationStore.Set(captchaId, clientId) io.WriteString(writer, captchaId) }
func (a Auth) Login() revel.Result { a.RenderArgs["needCaptcha"] = "true" a.RenderArgs["openRegister"] = "true" Captcha := struct { CaptchaId string }{ captcha.New(), } a.RenderArgs["Captcha"] = Captcha log.Println("captchaId:", Captcha.CaptchaId) return a.RenderTemplate("home/login.html") }
func RegisterForm(w http.ResponseWriter, req *http.Request, ctx *models.Context) (err error) { if ctx.User != nil { http.Redirect(w, req, reverse("logout"), http.StatusSeeOther) return nil } ctx.Data["title"] = "Register" ctx.Data["cap"] = captcha.New() return T("register.html").Execute(w, map[string]interface{}{ "ctx": ctx, "fbLoginLink": FbConfig().AuthCodeURL(models.GenUUID()), "glLoginLink": GlConfig().AuthCodeURL(models.GenUUID()), }) }
func showFormHandler(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/" { http.NotFound(w, r) return } d := struct { CaptchaId string }{ captcha.New(), } if err := formTemplate.Execute(w, &d); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } }
func GetImageCaptcha(c *gin.Context) { session := sessions.Default(c) captchaId := captcha.New() bytes := captcha.RandomDigits(4) captcheString := util.GetCaptchaString(bytes) session.Set(constant.LOGIN_CAPTCHA, captcheString) Logger.Debug("new captcha:%v", captcheString) session.Save() image := captcha.NewImage(captchaId, bytes, captcha.StdWidth/2, captcha.StdHeight/2) _, err := image.WriteTo(c.Writer) if err != nil { Logger.Error("error occured when writing captcha image to response") } }
func (self httpFrontend) new_captcha(wr http.ResponseWriter, r *http.Request) { s, err := self.store.Get(r, self.name) if err == nil { captcha_id := captcha.New() s.Values["captcha_id"] = captcha_id s.Save(r, wr) redirect_url := fmt.Sprintf("%scaptcha/%s.png", self.prefix, captcha_id) // redirect to the image http.Redirect(wr, r, redirect_url, 302) } else { // todo: send a "this is broken" image wr.WriteHeader(500) } }
func (self *CaptchaContext) Challenge(w http.ResponseWriter, r *http.Request, edge string) *ProxyError { captchaId := r.PostFormValue("captchaId") solution := r.PostFormValue("captchaSolution") // Verify the input. if captcha.VerifyString(captchaId, solution) { token, err := self.GenerateToken() if err != nil { return &ProxyError{ Code: 500, Msg: "Unable to generate token value.", Err: err, } } // Strip the port off, since I cannot use them in the cookie. parts := strings.Split(edge, ":") http.SetCookie(w, &http.Cookie{ Name: HumanCookieName, Value: token, Expires: time.Now().Add(self.ValidDuration), Domain: "." + parts[0], Path: "/", }) http.Redirect(w, r, r.URL.Path, 302) return nil } // Deal with displaying the Captcha. if strings.HasPrefix(r.URL.Path, "/captcha/") { self.Generator.ServeHTTP(w, r) return nil } else { if err := captchaTemplate.Execute(w, &struct{ CaptchaId string }{captcha.New()}); err != nil { return &ProxyError{ Code: 500, Msg: "Unable to generate captcha page.", Err: err, } } return nil } }
// renderPost builds on 'render' but is specifically for showing a post's page. // Namely, it handles the population of the "add comment" form. func renderPost(w http.ResponseWriter, post *Post, formError, formAuthor, formEmail, formComment string) { render(w, "post", struct { *Post FormCaptchaId string FormError string FormAuthor string FormEmail string FormComment string }{ Post: post, FormCaptchaId: captcha.New(), FormError: formError, FormAuthor: formAuthor, FormEmail: formEmail, FormComment: formComment, }) }
// 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()}) }
// 生成验证码 func (this *UserController) NewCaptcha() { captchaStr := captcha.New() //生成唯一的id this.SetSession("captchaStr", captchaStr) //将该字符串放入session中 captcha.WriteImage(this.Ctx.ResponseWriter, captchaStr, captcha.StdWidth, captcha.StdHeight) //将验证码输出到浏览器 return }
// GetKey generates a CAPTCHA ID and returns it. This can be combined // with the solution to the returned CAPTCHA to authenticate certain // API functions. The CAPTCHAs can be accessed at /captcha/<id>.png or // /captcha/<id>.wav. func (*Api) GetKey(ctx *jas.Context) { ctx.Data = captcha.New() }
// wrapAuthHandler返回符合 go.auth包要求签名的函数. func wrapAuthHandler(handler *Handler) func(w http.ResponseWriter, r *http.Request, u auth.User) { return func(w http.ResponseWriter, r *http.Request, u auth.User) { c := handler.DB.C(USERS) user := User{} session, _ := store.Get(r, "user") c.Find(bson.M{"username": u.Id()}).One(&user) //关联github帐号,直接登录 if user.Provider == GITHUB_COM { session.Values["username"] = user.Username session.Save(r, w) http.Redirect(w, r, "/", http.StatusSeeOther) } form := wtforms.NewForm(wtforms.NewTextField("username", "用户名", "", wtforms.Required{}), wtforms.NewPasswordField("password", "密码", wtforms.Required{})) session.Values[GITHUB_EMAIL] = u.Email() session.Values[GITHUB_ID] = u.Id() session.Values[GITHUB_LINK] = u.Link() session.Values[GITHUB_NAME] = u.Name() session.Values[GITHUB_ORG] = u.Org() session.Values[GITHUB_PICTURE] = u.Picture() session.Values[GITHUB_PROVIDER] = u.Provider() session.Save(r, w) //关联已有帐号 if handler.Request.Method == "POST" { if form.Validate(handler.Request) { user := User{} err := c.Find(bson.M{"username": form.Value("username")}).One(&user) if err != nil { form.AddError("username", "该用户不存在") handler.renderTemplate("accoun/auth_login.html", BASE, map[string]interface{}{"form": form}) return } if user.Password != encryptPassword(form.Value("password"), user.Salt) { form.AddError("password", "密码和用户名不匹配") handler.renderTemplate("account/auth_login.html", BASE, map[string]interface{}{"form": form, "captchaId": captcha.New()}) return } c.UpdateId(user.Id_, bson.M{"$set": bson.M{ "emal": session.Values[GITHUB_EMAIL], "accountref": session.Values[GITHUB_NAME], "username": session.Values[GITHUB_ID], "idref": session.Values[GITHUB_ID], "linkref": session.Values[GITHUB_LINK], "orgref": session.Values[GITHUB_ORG], "pictureref": session.Values[GITHUB_PICTURE], "provider": session.Values[GITHUB_PROVIDER], }}) deleteGithubValues(session) session.Values["username"] = u.Name() session.Save(r, w) http.Redirect(handler.ResponseWriter, handler.Request, "/", http.StatusFound) } } handler.renderTemplate("account/auth_login.html", BASE, map[string]interface{}{"form": form}) } }
// 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: /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()}) }
func WriteAccessEmailPage(w http.ResponseWriter, uid string, captcha_error bool) { writeHtmlWithValues(w, "captcha.html", &AccessEmailPageValues{uid, captcha_error, captcha.New()}) }
// TestEmailHandlerTimeout tests what happens after a refresh func TestEmailHandlerTimeout(t *testing.T) { verifyCaptcha = func(r *http.Request) bool { return true } // hack the captcha //*logfile = os.DevNull *refreshTime = 10 * time.Nanosecond // Really quick... //flag.Parse() c3 := setup() // Timer is started cwd, _ := os.Getwd() c3.route(cwd) ts := httptest.NewServer(c3.r) t1 := time.Now() defer ts.Close() res, err := http.Get(ts.URL) if err != nil { log.Fatal(err) } greeting, err := ioutil.ReadAll(res.Body) res.Body.Close() v := &url.Values{} v.Add("email", "*****@*****.**") v.Add("subject", "hello world") v.Add("message", "from test") fmt.Println("Fake:", captcha.New()) c3.rw.RLock() oldkey := c3.URLKey c3.rw.RUnlock() var t2 time.Time for { time.Sleep(10 * time.Nanosecond) // Wait for key to change if oldkey != c3.URLKey { t2 = time.Now() break } } fmt.Printf("Took %s to change keys\n", t2.Sub(t1)) res, err = http.PostForm(ts.URL+"/"+oldkey+"/send", *v) if err != nil { fmt.Println(err) t.FailNow() } greeting, err = ioutil.ReadAll(res.Body) res.Body.Close() if err != nil { fmt.Println(err) t.FailNow() } keyline := `Your message was not sent: Bad endpoint.` if !strings.Contains(string(greeting), keyline) { fmt.Println("\t"+redwanted, keyline) fmt.Println("\t" + grep(greeting, `Your message`)) if *debug { fmt.Println(string(greeting)) } t.FailNow() } // fmt.Println("\tFound it :)") // fmt.Println() return }