Fetch the repository succeeded.
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)
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。