🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
##### 验证码 为了防止被暴力撞密码,基本的验证码策略还是要是做的。好在 `beego`直接内置了验证码的库,所以这事就很简单了。。。 首先引入 `beego` 的 `cache` 模块和 `captcha` 模块 ~~~ # http/controllers/login.go import (    "github.com/astaxie/beego/cache"    "github.com/astaxie/beego/utils/captcha" ) ~~~ 然后我们需要增加验证码初始化的代码。开启 `cache`,验证码的字数,长度宽度什么的。 ~~~ # http/controllers/login.go func init() { // 生成验证码,一定要写在构造函数里面,要不然第一次打开页面有可能是X store := cache.NewMemoryCache() cpt := captcha.NewWithFilter("/captcha/", store) cpt.ChallengeNums = 4 cpt.StdWidth = 80 cpt.StdHeight = 40 cpt.FieldCaptchaName = "captcha" cpt.FieldIDName = "captchas" } ~~~ 考虑这个验证码其实挺考验眼力的。。。所以我们只在用户认证失败的时候再增加验证码。认证失败的信息通过 `session` 来记录 ~~~ # http/controllers/login.go    loginFailed := this.GetSession("loginFailed")    if loginFailed != nil {        this.Data["captcha"] = true   } ~~~ 在模板里,我们把这块根据 `captcha` 的值做个判断,来决定是否开启验证码。 ~~~ # http/views/login.tpl           {{if .captcha}}            <div class="form-group">                <div class="row">                    <div class="col-md-6">                        <input  class="form-control" name="captcha"  type="text" placeholder="Captcha" required>                    </div>                    <div class="col-md-6">                       {{create_captcha}}                    </div>                </div>            </div>           {{end}}     ~~~ 如果开启了验证码,那么拿收到的验证码做验证就好了,验证方法也给封装好了,`beego` 很贴心呢。 ~~~ # http/controllers/login.go    if _, ok := this.Ctx.Request.Form["captcha"]; ok {        if !cpt.VerifyReq(this.Ctx.Request) {            beego.Notice(fmt.Sprintf("%s - - [%s] Login Failed: Captcha Wrong", clientIP, logtime))            this.Ctx.Redirect(302, fmt.Sprintf("/login?loginFailed=3&target=%s", target))            return       }   } ~~~