##### 驗證碼
為了防止被暴力撞密碼,基本的驗證碼策略還是要是做的。好在 `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
? ? ? }
? }
~~~
- go環境搭建
- 解決go get網絡慢的問題
- beego的安裝
- bee的安裝
- 編輯器
- go module
- 配置文件詳解
- 配置文件其他說明
- 路由方法
- 路由
- 數據校驗
- 校驗函數
- 頁面跳轉
- 獲取前端數據
- json文件的獲取
- xsrf的用法
- xsrf的防護
- srfs和json的搭配
- flash的用法
- 過濾器
- url反轉
- 各類數據的處理
- 模板函數
- 內置模板函數
- 自定義模板函數
- 模板
- 模板處理
- 模板渲染
- 視圖文件的處理
- 靜態文件
- 請求方式判斷
- 驗證碼
- 另一種方法
- 分頁類
- session
- 登錄判斷
- orm模塊
- 使用方法
- mysql的安裝
- 安裝orm及驅動
- 建立模型
- 自定義模型
- 增刪改查
- 高級查詢
- 常見問題匯總
- 代碼收藏
- 打包部署
- go build打包
- utils收藏
- 新goer容易犯的錯
- 字符串操作