You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

106 lines
3.0 KiB

package data
import (
"context"
"customer/internal/biz"
"database/sql"
"fmt"
"github.com/go-kratos/kratos/v2/errors"
"github.com/golang-jwt/jwt/v4"
"gorm.io/gorm"
"time"
)
type CustomerData struct {
data *Data
}
func NewCusomerData(data *Data) *CustomerData {
return &CustomerData{data: data}
}
func (this *CustomerData) SetVerifyCode(telephone string, code string, ex int64) error {
status := this.data.Rdb.Set(context.Background(), "CVC:"+telephone, code, time.Duration(ex)*time.Second)
if _, err := status.Result(); err != nil {
return err
}
return nil
}
func (this *CustomerData) GetVerifyCode(telephone string) string {
key := "CVC:" + telephone
status := this.data.Rdb.Get(context.Background(), key)
code, err := status.Result()
if err != nil {
return ""
}
return code
}
func (this *CustomerData) GetCusomerByTelephone(telephone string) (*biz.Customer, error) {
customer := &biz.Customer{}
result := this.data.Mdb.Where("telephone = ?", telephone).First(customer)
if result.Error == nil && customer.ID > 0 {
return customer, nil
}
if result.Error != nil && errors.Is(result.Error, gorm.ErrRecordNotFound) {
customer.Telephone = telephone
customer.Name = sql.NullString{Valid: false}
customer.Email = sql.NullString{Valid: false}
customer.Wechat = sql.NullString{Valid: false}
resultCreate := this.data.Mdb.Create(customer)
if resultCreate.Error != nil {
return nil, resultCreate.Error
} else {
return customer, nil
}
}
return nil, result.Error
}
func (this *CustomerData) GenerateTokenAndSave(c *biz.Customer, duration time.Duration, secret string) (string, error) {
claims := jwt.RegisteredClaims{
Issuer: "LaoMaDJ", // 签发机构
Subject: "customer-authentication", // 说明
Audience: []string{"customer", "other"}, // 签发给谁使用
ExpiresAt: jwt.NewNumericDate(time.Now().Add(duration)), // 有效期
NotBefore: nil, // 何时启用
IssuedAt: jwt.NewNumericDate(time.Now()), // 签发时间
ID: fmt.Sprintf("%d", c.ID), // 用户ID
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
signedToken, err := token.SignedString([]byte(secret))
if err != nil {
return "", err
}
c.Token = signedToken
c.TokenCreatedAt = sql.NullTime{
Time: time.Now(),
Valid: true,
}
if result := this.data.Mdb.Save(c); result.Error != nil {
return "", result.Error
}
return signedToken, nil
}
func (this *CustomerData) GetToken(id interface{}) (string, error) {
customer := &biz.Customer{}
result := this.data.Mdb.Where("id = ?", id).First(customer)
if result.Error != nil && customer.ID > 0 {
return "", result.Error
}
return customer.Token, nil
}
func (cd CustomerData) DelToken(id interface{}) error {
c := &biz.Customer{}
if result := cd.data.Mdb.First(c, id); result.Error != nil {
return result.Error
}
c.Token = ""
c.TokenCreatedAt = sql.NullTime{Valid: false}
cd.data.Mdb.Save(c)
return nil
}