当前位置: 首页>>代码示例>>Golang>>正文


Golang captcha.VerifyString函数代码示例

本文整理汇总了Golang中github.com/dchest/captcha.VerifyString函数的典型用法代码示例。如果您正苦于以下问题:Golang VerifyString函数的具体用法?Golang VerifyString怎么用?Golang VerifyString使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了VerifyString函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: DoLogin

func (a Auth) DoLogin(email, pwd, validationCode, captchaId string) revel.Result {
	log.Println("email:", email, "validationCode:", validationCode, "captchaId:", captchaId)
	ok := app.NewOk()
	ok.Ok = a.Validation.Required(captcha.VerifyString(captchaId, validationCode)).Ok
	if !ok.Ok {
		ok.Msg = "captcha"
		return a.RenderJson(ok)
	}
	ok.Ok = a.Validation.Required(email).Ok
	if !ok.Ok {
		ok.Msg = "email"
		return a.RenderJson(ok)
	}
	ok.Ok = a.Validation.Email(email).Ok
	if !ok.Ok {
		ok.Msg = "email"
		return a.RenderJson(ok)
	}

	if !a.checkAuth() {
		ok.Msg = "login"
		ok.Ok = false
	} else {
		ok.Next = app.NextJson{"href", "/index"}
		a.Session["user"] = email
		if email == "[email protected]" {
			ok.Msg = "admin"
		}
	}

	log.Println("set register session:", a.Session, "with resp:", ok)
	return a.RenderJson(ok)
}
开发者ID:netw0rm,项目名称:reweb,代码行数:33,代码来源:AuthController.go

示例2: Check

// 校验验证码
func (this *Captcha) Check(req *http.Request, res http.ResponseWriter) {
	req.ParseForm()
	if ok := captcha.VerifyString(req.Form.Get(conf.ConfInstance.CaptchaIdName), req.Form.Get(conf.ConfInstance.CaptchaName)); !ok {
		res.WriteHeader(400)
		res.Write([]byte("验证码错误"))
	}
}
开发者ID:tmchojo,项目名称:as,代码行数:8,代码来源:captcha.go

示例3: LoginAction

// 用户登录表单提交
func (this *UserController) LoginAction() {
	flash := beego.NewFlash()
	user := &models.User{}
	err := this.ParseForm(user)

	if err != nil {
		beego.Error("用户登录失败:" + err.Error())
		flash.Error("用户登录失败!")
		flash.Store(&this.Controller)
		this.Redirect("/login", 302) //登录失败,重定向到登录页
		return
	}

	user.Password = models.MD5(user.Password) //将密码以MD5加密存储
	captchaCode := this.Input().Get("captcha")

	//判断验证码是否正确
	if !captcha.VerifyString(this.GetSession("captchaStr").(string), captchaCode) {
		flash.Error("验证码不正确!")
		flash.Store(&this.Controller)
		this.DelSession("captchaStr") //从session中清空
		this.Redirect("/login", 302)  //验证码不正确,重定向到登录页
		return
	} else {
		isAutoLogin := this.Input().Get("isAutoLogin") == "on" //是否自动登录

		u := models.Login(user) //成功返回user,失败返回nil

		if u != nil {
			maxAge := 0
			if isAutoLogin {
				maxAge = 72 * 24 * 60
			}
			this.Ctx.SetCookie("username", user.Username, maxAge, "/") //设置cookie
			this.Ctx.SetCookie("password", user.Password, maxAge, "/") //设置cookie

			u.Lastlogin = time.Now().Local() //设置最后登录时间
			u.Loginip = this.Ctx.Input.IP()  //获取客户端IP

			if !models.UserModify(u) { //用户登录成功后更新最后登录时间
				beego.Error("更新用户最后登录时间失败" + err.Error())
				flash.Error("更新用户最后登录时间失败!")
				flash.Store(&this.Controller)
			}

			this.SetSession("user", u) //将用户信息存放到Session中
			flash.Notice("用户" + u.Nickname + "登录成功!")
			flash.Store(&this.Controller)
			this.Redirect("/", 302) //登录成功
			return
		} else {
			flash.Error("用户名或密码不正确!")
			flash.Store(&this.Controller)
			this.Redirect("/login", 302) //登录失败,重定向到登录页
			return
		}
	}

}
开发者ID:a648132694,项目名称:goblog,代码行数:60,代码来源:user.go

示例4: processFormHandler

func processFormHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	if !captcha.VerifyString(r.FormValue("captchaId"), r.FormValue("captchaSolution")) {
		io.WriteString(w, "Wrong captcha solution! No robots allowed!\n")
	} else {
		io.WriteString(w, "Great job, human! You solved the captcha.\n")
	}
	io.WriteString(w, "<br><a href='/'>Try another one</a>")
}
开发者ID:senior7515,项目名称:captcha,代码行数:9,代码来源:main.go

示例5: CheckSession

// return true if this session has solved the last captcha given provided solution, otherwise false
func (cs *CaptchaServer) CheckSession(w http.ResponseWriter, r *http.Request, solution string) (bool, error) {
	s, err := cs.store.Get(r, cs.sessionName)
	if err == nil {
		id, ok := s.Values["captcha_id"]
		if ok {
			return captcha.VerifyString(id.(string), solution), nil
		}
	}
	return false, err
}
开发者ID:majestrate,项目名称:nntpchan,代码行数:11,代码来源:captcha.go

示例6: captchaServer

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 {
		}
	}
}
开发者ID:Elemarkef,项目名称:livechan,代码行数:11,代码来源:http.go

示例7: goodCaptchaSolution

/*
	Checks to make sure the user gave a valid CAPTCHA solution.
	(Note: if false is returned, this function takes care of serving a webpage to the user)
	Parameters:
		ctx:	the context of the http request
		id:		the id string for the captcha we are to check the solution against
		soln:	the solution the user submitted to the CAPTCHA
	Returns:
		bool:	true if the user entered a correct solution, false otherwise.
		string:	A string containing the error text as to why the solution was not accepted, or nil
		error:	Any error that was encountered
*/
func goodCaptchaSolution(ctx *web.Context, id, soln string) (bool, string, error) {
	//make sure we were given a non-empty ID
	if id == "" {
		return false, "INTERNAL ERROR", errors.New("Attempting to verify CAPTCHA with empty ID")
	} else if soln == "" { //Make sure they actually answered the CAPTCHA
		return false, "You must enter a solution to the CAPTCHA to generate a short link", nil
	} else if !captcha.VerifyString(ctx.Params["captcha_id"], soln) { //They didn't give a correct solution
		return false, "The solution to the CAPTCHA that you entered was incorrect", nil
	}
	//The user gave us a correct solution to the CAPTCHA
	return true, "", nil
}
开发者ID:JGets,项目名称:reduse,代码行数:24,代码来源:pageFunc.go

示例8: IsCaptchaValid

// IsCaptchaValid checks (when the app is not in the developing mode) if the
// captcha is correct for a particular name
func (Adapter *Adapter) IsCaptchaValid(page string) bool {
	value := strings.TrimSpace(Adapter.GetString(page + "-captcha-value"))
	id := strings.TrimSpace(Adapter.GetString(page + "-captcha-id"))
	if !Adapter.IsProductionMode() {
		return true
	}

	if !Adapter.IsCaptchaRequired(page) {
		return true
	}
	return captcha.VerifyString(id, value)

}
开发者ID:cristian-sima,项目名称:Wisply,代码行数:15,代码来源:adapter.go

示例9: RegisterAction

// 用户注册表单提交
func (this *UserController) RegisterAction() {
	flash := beego.NewFlash()
	user := &models.User{}
	err := this.ParseForm(user)
	if err != nil {
		beego.Error("用户注册失败:" + err.Error())
		flash.Error("注册用户失败!")
		flash.Store(&this.Controller)
		this.Redirect("/register", 302) //注册失败,重定向到注册页
		return
	}

	user.Password = models.MD5(user.Password) //将密码以MD5加密存储
	user.Registed = time.Now().Local()        //用户注册时间
	user.Lastlogin = time.Now().Local()       //用户最后登录时间
	user.Registeip = this.Ctx.Input.IP()      //用户注册的ip

	captchaCode := this.Input().Get("captcha")

	//判断验证码是否正确
	if !captcha.VerifyString(this.GetSession("captchaStr").(string), captchaCode) {
		flash.Error("验证码不正确!")
		flash.Store(&this.Controller)
		this.DelSession("captchaStr")   //从session中清空
		this.Redirect("/register", 302) //验证码不正确,重定向到登录页
		return
	} else {
		if models.CheckUser(user.Username) { //判断该用户是否已经存在
			flash.Error("该用户已存在!")
			flash.Store(&this.Controller)
			this.Redirect("/register", 302) //该用户已存在,重定向到注册页
			return
		} else {
			err = models.RegisterUser(user) //用户注册
			if err != nil {
				flash.Error("注册用户失败!")
				flash.Store(&this.Controller)
				this.Redirect("/register", 302) //验证码不正确,重定向到注册页
				return
			}
		}

	}
	flash.Notice("注册成功!")
	flash.Store(&this.Controller)
	this.Redirect("/login", 302) //注册成功,重定向到登录页
	return
}
开发者ID:a648132694,项目名称:goblog,代码行数:49,代码来源:user.go

示例10: verifyCaptcha

func verifyCaptcha(writer http.ResponseWriter, request *http.Request) {
	captchaId := request.URL.Query().Get("captchaId")
	verifyString := request.URL.Query().Get("verifyString")

	clientId := validationStore.Get(captchaId, true)

	result := captcha.VerifyString(captchaId, verifyString)
	if result {
		privateKey := userStore.Get(clientId, false)
		md5String := fmt.Sprintf("%x", md5.Sum([]byte(privateKey+captchaId)))
		validationStore.Set(md5String, clientId)
		io.WriteString(writer, md5String)
	} else {
		io.WriteString(writer, "fail")
	}
}
开发者ID:thbourlove,项目名称:ecaptcha,代码行数:16,代码来源:main.go

示例11: login

func login(w http.ResponseWriter, r *http.Request, s sessions.Session, logger *log.Logger) {
	r.ParseForm()
	username := r.PostForm.Get("username")
	password := r.PostForm.Get("password")
	checkcode := r.PostForm.Get("checkcode")

	code := s.Get("checkcode")
	if !captcha.VerifyString(code.(string), checkcode) {
		w.Write(jsonResponse(map[string]interface{}{"status": false, "msg": "验证码错误"}))
	} else {
		user := &data.User{Logger: logger}
		if user.Check(username, password) {
			s.Set("useradmin", username)
			w.Write(jsonResponse(map[string]interface{}{"status": true, "msg": "success"}))
		} else {
			w.Write(jsonResponse(map[string]interface{}{"status": false, "msg": "用户名或密码错误"}))
		}
	}
}
开发者ID:kyf,项目名称:compass,代码行数:19,代码来源:login_action.go

示例12: Challenge

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
	}
}
开发者ID:MadMarx,项目名称:mirror,代码行数:42,代码来源:cookie.go

示例13: addComment

// addComment responds to a POST request for adding a comment to a post
// with an ident matching "postname". If such a post cannot be found,
// a 404 page is shown.
// Form data is trimmed and the CAPTCHA is verified before anything else.
// Finally, we add the comment but make sure to wrap it in an addCommentLocker.
// This makes it so only a single comment can be added at a time for one
// particular entry. This allows us to rely on the existing cache to provide
// a unique identifier as a comment file name. (i.e., an incrementing integer.)
func addComment(w http.ResponseWriter, req *http.Request) {
	// render404(w, "add comment")
	// return

	vars := mux.Vars(req)
	post := forceValidPost(w, vars["postname"])
	if post == nil {
		return
	}

	// Get the form values.
	author := strings.TrimSpace(req.FormValue("plato"))
	email := strings.TrimSpace(req.FormValue("email"))
	comment := strings.TrimSpace(req.FormValue("cauchy"))

	// First check the captcha before anything else.
	captchaId := req.FormValue("captchaid")
	userTest := req.FormValue("captcha")
	if !captcha.VerifyString(captchaId, userTest) {
		renderPost(w, post,
			"The CAPTCHA text you entered did not match the text in the "+
				"image. Please try again.", author, email, comment)
		return
	}

	// We need to make sure only one comment per post can be added at a time.
	// Namely, we need unique sequential identifiers for each comment.
	post.addCommentLocker.Lock()
	defer post.addCommentLocker.Unlock()

	// Add the comment and refresh the comment store for this post.
	// 'addComment' makes sure the input is valid and reports an
	// error otherwise.
	err := post.addComment(author, email, comment)
	if err == nil { // success!
		post.loadComments()
		http.Redirect(w, req, "/"+post.Ident+"#comments", http.StatusFound)
	} else { // failure... :-(
		renderPost(w, post, err.Error(), author, email, comment)
	}
}
开发者ID:jacobxk,项目名称:burntsushi-blog,代码行数:49,代码来源:blog.go

示例14: VerifyCAPTCHA

// VerifyCAPTCHA accepts a *http.Request and verifies that the given
// 'captcha' form is valid. This is a string of the form
// "id:solution". It will return IncorrectCAPTCHAError if the solution
// or ID is invalid.
func VerifyCAPTCHA(req *http.Request) error {
	// Get the "captcha" form value.
	solution := req.FormValue("captcha")

	// Find the point to split the form value at. If it's not found in
	// the string, return the InvalidCAPTCHAFormat error.
	index := strings.Index(solution, ":")
	if index < 0 {
		return InvalidCAPTCHAFormat
	}

	// If that was successful, try to verify it. If it returns false,
	// the ID or solution was invalid.
	if !captcha.VerifyString(solution[:index], solution[index+1:]) {
		return IncorrectCAPTCHA
	}

	// If we get to this point, then it was successfully validated and
	// we can return nil.
	return nil
}
开发者ID:rschulman,项目名称:nodeatlas,代码行数:25,代码来源:web.go

示例15: RegisterHandler

// 用户注册
// uri: /account/register{json:(|.json)}
func RegisterHandler(rw http.ResponseWriter, req *http.Request) {
	if _, ok := filter.CurrentUser(req); ok {
		util.Redirect(rw, req, "/")
		return
	}

	vars := mux.Vars(req)
	username := req.PostFormValue("username")
	// 请求注册页面
	if username == "" || req.Method != "POST" || vars["json"] == "" {
		filter.SetData(req, map[string]interface{}{"captchaId": captcha.NewLen(4)})
		req.Form.Set(filter.CONTENT_TPL_KEY, "/template/register.html")
		return
	}

	// 校验验证码
	if !captcha.VerifyString(req.PostFormValue("captchaid"), req.PostFormValue("captchaSolution")) {
		fmt.Fprint(rw, `{"ok": 0, "error":"验证码错误"}`)
		return
	}

	// 入库
	errMsg, err := service.CreateUser(req.PostForm)
	if err != nil {
		// bugfix:http://studygolang.com/topics/255
		if errMsg == "" {
			errMsg = err.Error()
		}
		fmt.Fprint(rw, `{"ok": 0, "error":"`, errMsg, `"}`)
		return
	}

	// 注册成功,自动为其登录
	setCookie(rw, req, req.PostFormValue("username"))
	// 发送欢迎邮件
	go sendWelcomeMail([]string{req.PostFormValue("email")})
	fmt.Fprint(rw, `{"ok": 1, "msg":"注册成功"}`)
}
开发者ID:bluefchen,项目名称:studygolang,代码行数:40,代码来源:account.go


注:本文中的github.com/dchest/captcha.VerifyString函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。