刷新验证码

This commit is contained in:
suyl
2021-07-05 18:04:29 +08:00
parent 9f8633a914
commit 17701fe1ac
8 changed files with 179 additions and 3 deletions

View File

@@ -0,0 +1,7 @@
package controllers
import "git.rosy.net.cn/jx-print/globals"
func init() {
globals.SugarLogger.Debugf("test init ...")
}

View File

@@ -0,0 +1,10 @@
package controllers
import (
"git.rosy.net.cn/jx-print/utils"
"github.com/gin-gonic/gin"
)
func RefreshCode(c *gin.Context){
utils.Captcha(c,4)
}

14
globals/globals.go Normal file
View File

@@ -0,0 +1,14 @@
package globals
import (
"go.uber.org/zap"
)
var (
SugarLogger *zap.SugaredLogger
)
func init() {
logger, _ := zap.NewDevelopment()
SugarLogger = logger.Sugar()
}

49
main.go
View File

@@ -1,5 +1,52 @@
package jx_print package main
import (
"fmt"
_ "git.rosy.net.cn/jx-print/controllers"
"git.rosy.net.cn/jx-print/model"
"git.rosy.net.cn/jx-print/routers"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
"github.com/gin-gonic/gin"
"time"
)
func main() { func main() {
gin.DisableConsoleColor()
r := gin.New()
r.Use(session(model.SessionKey))
// LoggerWithFormatter middleware will write the logs to gin.DefaultWriter
// By default gin.DefaultWriter = os.Stdout
r.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
// your custom format
return fmt.Sprintf("%s - [%s] \"%s %s %d \" %s\"\n",
param.ClientIP,
param.TimeStamp.Format(time.RFC3339),
param.Method,
param.Path,
param.StatusCode,
param.ErrorMessage,
)
}))
r.Use(gin.Recovery())
routers.Init(r)
r.Run()
}
// 中间件处理session
func session(keyPairs string) gin.HandlerFunc {
store := sessionConfig()
return sessions.Sessions(keyPairs, store)
}
func sessionConfig() sessions.Store {
sessionMaxAge := 3600
sessionSecret := model.SessionKey
var store sessions.Store
store = cookie.NewStore([]byte(sessionSecret))
store.Options(sessions.Options{
MaxAge: sessionMaxAge, //seconds
Path: "/",
})
return store
} }

15
model/model.go Normal file
View File

@@ -0,0 +1,15 @@
package model
import "time"
const (
SessionKey = "jxCode"
)
type ModelIDCULD struct {
ID int `json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
LastOperator string `json:"last_operator"`
DeletedAt time.Time `json:"deleted_at"`
}

13
routers/router.go Normal file
View File

@@ -0,0 +1,13 @@
package routers
import (
"git.rosy.net.cn/jx-print/controllers"
"github.com/gin-gonic/gin"
)
func Init(r *gin.Engine){
v2 := r.Group("/v2")
//user
user := v2.Group("/user")
user.POST("/refreshCode",controllers.RefreshCode)
}

2
services/user.go Normal file
View File

@@ -0,0 +1,2 @@
package services

68
utils/utils.go Normal file
View File

@@ -0,0 +1,68 @@
package utils
import (
"bytes"
"git.rosy.net.cn/jx-print/model"
"github.com/dchest/captcha"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"net/http"
"time"
)
func Captcha(c *gin.Context, length ...int) {
l := captcha.DefaultLen
w, h := 107, 36
if len(length) == 1 {
l = length[0]
}
if len(length) == 2 {
w = length[1]
}
if len(length) == 3 {
h = length[2]
}
captchaId := captcha.NewLen(l)
session := sessions.Default(c)
session.Set(model.SessionKey, captchaId)
_ = session.Save()
_ = Serve(c.Writer, c.Request, captchaId, ".png", "zh", false, w, h)
}
func CaptchaVerify(c *gin.Context, code string) bool {
session := sessions.Default(c)
if captchaId := session.Get(model.SessionKey); captchaId != nil {
session.Delete(model.SessionKey)
_ = session.Save()
if captcha.VerifyString(captchaId.(string), code) {
return true
} else {
return false
}
} else {
return false
}
}
func Serve(w http.ResponseWriter, r *http.Request, id, ext, lang string, download bool, width, height int) error {
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
w.Header().Set("Pragma", "no-cache")
w.Header().Set("Expires", "0")
var content bytes.Buffer
switch ext {
case ".png":
w.Header().Set("Content-Type", "image/png")
_ = captcha.WriteImage(&content, id, width, height)
case ".wav":
w.Header().Set("Content-Type", "audio/x-wav")
_ = captcha.WriteAudio(&content, id, lang)
default:
return captcha.ErrNotFound
}
if download {
w.Header().Set("Content-Type", "application/octet-stream")
}
http.ServeContent(w, r, id+ext, time.Time{}, bytes.NewReader(content.Bytes()))
return nil
}