7 Star 23 Fork 31

go-course/go8

Create your Gitee Account
Explore and code with more than 14 million developers,Free private repositories !:)
Sign up
文件
Clone or Download
app.go 2.15 KB
Copy Edit Raw Blame History
Mr.Yu authored 2022-12-24 16:57 +08:00 . add code verify
package code
import (
"context"
"fmt"
"hash/fnv"
"math/rand"
"net/http"
"strconv"
"strings"
"time"
"github.com/go-playground/validator/v10"
"github.com/infraboard/mcube/exception"
)
const (
AppName = "code"
)
var (
validate = validator.New()
)
// NewIssueCodeRequest todo
func NewIssueCodeRequest() *IssueCodeRequest {
return &IssueCodeRequest{}
}
func (req *IssueCodeRequest) Validate() error {
return validate.Struct(req)
}
type Service interface {
RPCServer
IssueCode(context.Context, *IssueCodeRequest) (*IssueCodeResponse, error)
}
// NewCode todo
func NewCode(req *IssueCodeRequest) (*Code, error) {
if err := req.Validate(); err != nil {
return nil, exception.NewBadRequest("validate issue code request error, %s", err)
}
c := &Code{
Code: GenRandomCode(6),
Username: req.Username,
IssueAt: time.Now().UnixMilli(),
ExpiredMinite: 10,
}
c.Id = HashID(c.Username, c.Code)
return c, nil
}
// IsExpired todo
func (c *Code) IsExpired() bool {
return time.Since(time.UnixMilli(c.IssueAt)).Minutes() > float64(c.ExpiredMinite)
}
// GenRandomCode todo 000001 100001 10000
func GenRandomCode(length uint) string {
numbers := []string{}
rand.Seed(time.Now().Unix())
for i := 0; i < int(length); i++ {
c := rand.Intn(9)
// 第一位不能为0
if i == 0 && c == 0 {
c = 1
}
numbers = append(numbers, strconv.Itoa(c))
}
return strings.Join(numbers, "")
}
// HashID todo
func HashID(username, code string) string {
hash := fnv.New32a()
hash.Write([]byte(username))
hash.Write([]byte(code))
return fmt.Sprintf("%x", hash.Sum32())
}
func NewVerifyCodeRequest(username, code string) *VerifyCodeRequest {
return &VerifyCodeRequest{
Username: username,
Code: code,
}
}
// HashID todo
func (req *VerifyCodeRequest) HashID() string {
return HashID(req.Username, req.Code)
}
// Validate todo
func (req *VerifyCodeRequest) Validate() error {
return validate.Struct(req)
}
// 优先从认证头中获取, 如果头没有从Query String中获取
func GetCodeFromHTTP(r *http.Request) string {
code := r.Header.Get(CODE_HEADER_KEY)
if code != "" {
return code
}
return r.URL.Query().Get(CODE_QUERY_KEY)
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/go-course/go8.git
git@gitee.com:go-course/go8.git
go-course
go8
go8
6a8978f41a84

Search