Browse Source

配置文件修改

huangyan 7 months ago
parent
commit
023f930458
6 changed files with 221 additions and 0 deletions
  1. 25 0
      configs/config.go
  2. 48 0
      utils/create_code.go
  3. 59 0
      utils/create_token.go
  4. 13 0
      utils/md5.go
  5. 55 0
      utils/sms.go
  6. 21 0
      utils/token.go

+ 25 - 0
configs/config.go

@@ -0,0 +1,25 @@
+package configs
+
+import (
+	"github.com/spf13/viper"
+	"os"
+)
+
+var Config *viper.Viper
+
+func init() {
+	Config = viper.New()
+	dir, _ := os.Getwd()
+
+	_, err := os.Stat(dir + "/config.yaml")
+	if err != nil {
+		panic(any("配置文件不存在,请检查配置文件!"))
+	}
+
+	Config.SetConfigName("config")
+	Config.SetConfigType("yaml")
+	Config.AddConfigPath(dir)
+	if err := Config.ReadInConfig(); err != nil {
+		panic(any(err.Error()))
+	}
+}

+ 48 - 0
utils/create_code.go

@@ -0,0 +1,48 @@
+package utils
+
+import (
+	"Ic_ouath/app/e"
+	"Ic_ouath/configs"
+	"Ic_ouath/global"
+	"context"
+	"fmt"
+	"go.uber.org/zap"
+	"math/rand"
+	"time"
+)
+
+func CreatCode() string {
+	const chars = "0123456789"
+	result := make([]byte, 6)
+	rand.Seed(time.Now().UnixNano())
+	for i := range result {
+		index := rand.Intn(len(chars))
+		result[i] = chars[index]
+	}
+	return string(result)
+}
+
+func SendModel(phone string) e.Rescode {
+	ctx := context.Background()
+	ss := NewSMS(configs.Config.GetString("subMail.appid"), configs.Config.GetString("subMail.signature"))
+	result, err := global.Rdb.Exists(ctx, phone).Result()
+	if result == 1 {
+		fmt.Println("验证码已经发送", zap.Error(err))
+		return e.HasSend
+	}
+	if err != nil {
+		fmt.Println("redis查询出现异常", zap.Error(err))
+		return e.TheSystemIsAbnormal
+	}
+	code := CreatCode()
+	content := fmt.Sprintf("【冷链智控系统】您的短信验证码:%s,请在1分钟内输入", code)
+	res, err := ss.Send(phone, content)
+	if err != nil || res.Status != SUCCESS {
+		fmt.Println("发送短信验证码出现异常", zap.Any("res", res), zap.Error(err))
+		return e.AnExceptionOccursWhenSendingAnSMSVerificationCode
+	} else {
+		//验证码装入redis并且设置过期时间
+		err = global.Rdb.Set(ctx, phone, code, 60*time.Second).Err()
+		return e.SUCCESS
+	}
+}

+ 59 - 0
utils/create_token.go

@@ -0,0 +1,59 @@
+package utils
+
+import (
+	"Ic_ouath/app/e"
+	"Ic_ouath/configs"
+	"errors"
+	"github.com/golang-jwt/jwt/v4"
+	"time"
+)
+
+type MyClaims struct {
+	UserId   uint   `json:"user_id"`
+	UserName string `json:"user_name"`
+	Role     string `json:"role"`
+	jwt.RegisteredClaims
+}
+
+const TokenExpireDuration = time.Hour * 72
+
+func CreateToken(userId uint, userName, role string) (string, error) {
+	claims := MyClaims{
+		UserId:   userId,
+		UserName: userName,
+		Role:     role,
+		RegisteredClaims: jwt.RegisteredClaims{
+			ExpiresAt: jwt.NewNumericDate(time.Now().Add(TokenExpireDuration)),
+			Issuer:    configs.Config.GetString("jwt.Issuer"),
+		},
+	}
+	var mySerect = []byte(configs.Config.GetString("jwt.secret"))
+	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
+	return token.SignedString(mySerect)
+}
+func ParseToken(tokenStr string) (*MyClaims, e.Rescode) {
+	// 使用全局配置中的密钥对token进行解析。
+	var mySecret = []byte(configs.Config.GetString("jwt.secret"))
+	// 尝试解析并验证JWT令牌。
+	claims := new(MyClaims)
+	token, err := jwt.ParseWithClaims(tokenStr, claims, func(token *jwt.Token) (interface{}, error) {
+		return mySecret, nil
+	})
+
+	if err != nil {
+		if errors.Is(err, jwt.ErrSignatureInvalid) || errors.Is(err, jwt.ErrInvalidKey) {
+			return nil, e.TokenIsInvalid
+		} else if ve, ok := err.(*jwt.ValidationError); ok && ve.Errors&jwt.ValidationErrorExpired != 0 {
+			return nil, e.TokenIsExpired
+		}
+		return nil, e.TokenIsInvalid
+	}
+
+	// 验证令牌是否有效。
+	if !token.Valid {
+		return nil, e.TokenIsInvalid
+	}
+
+	// 如果令牌有效,则返回解析出的声明信息。
+	return claims, e.SUCCESS
+}

+ 13 - 0
utils/md5.go

@@ -0,0 +1,13 @@
+package utils
+
+import (
+	"crypto/md5"
+	"encoding/hex"
+)
+
+func MD5(password string) string {
+	bytes := []byte(password)
+	sum := md5.Sum(bytes)
+	toString := hex.EncodeToString(sum[:])
+	return toString
+}

+ 55 - 0
utils/sms.go

@@ -0,0 +1,55 @@
+package utils
+
+import (
+	"encoding/json"
+	"github.com/go-resty/resty/v2"
+)
+
+const (
+	SUCCESS = "success"
+)
+
+type SMS struct {
+	Appid     string
+	Signature string
+}
+
+func NewSMS(appid, signature string) *SMS {
+	return &SMS{
+		Appid:     appid,
+		Signature: signature,
+	}
+}
+
+type SendRes struct {
+	Status  string `json:"status"`
+	Send_id string `json:"send_id"`
+	Fee     int    `json:"fee"`
+	Msg     string `json:"msg"`
+	Code    int    `json:"code"`
+}
+
+// Send 短信发送
+func (t *SMS) Send(to, content string) (SendRes, error) {
+	client := resty.New()
+	resp, err := client.R().
+		SetHeader("Content-Type", "application/x-www-form-urlencoded").
+		SetFormData(map[string]string{
+			"appid":     t.Appid,
+			"signature": t.Signature,
+			"to":        to,
+			"content":   content,
+		}).
+		SetResult(&SendRes{}).
+		Post("https://api-v4.mysubmail.com/sms/send.json")
+
+	if err != nil {
+		return SendRes{}, err
+	}
+
+	temp := SendRes{}
+	if err = json.Unmarshal(resp.Body(), &temp); err != nil {
+		return SendRes{}, err
+	}
+	return temp, nil
+}

+ 21 - 0
utils/token.go

@@ -0,0 +1,21 @@
+package utils
+
+import (
+	"Ic_ouath/app/e"
+	"Ic_ouath/global"
+	"Ic_ouath/models"
+)
+
+func Verification(token string) (bool, models.User) {
+	var user models.User
+	parseToken, err := ParseToken(token)
+	if err != e.SUCCESS {
+		return false, user
+	} else {
+		tx := global.DBLink.Where("id = ?", parseToken.UserId).First(&user)
+		if tx.RowsAffected > 0 {
+			return true, user
+		}
+		return false, user
+	}
+}