1
This commit is contained in:
77
common/service/common/base.go
Normal file
77
common/service/common/base.go
Normal file
@ -0,0 +1,77 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"go-admin/pkg/cryptohelper/jwthelper"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// 通过原生 token 获取登录用户 ID,判断是否登录。
|
||||
// 注:该方法未经过登录中间件,从原始 token 中解析出登录信息,而非从已解析的 token 串中获取登录信息。
|
||||
func GetUserIdByToken(ctx *gin.Context) int {
|
||||
token := ctx.GetHeader("token")
|
||||
if len(token) == 0 {
|
||||
return 0
|
||||
}
|
||||
// 解析token
|
||||
flag, rew := jwthelper.MidValidToken(token, 3)
|
||||
if flag < 0 || len(rew) == 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
loginUser := jwthelper.GetLoginUserJwt(rew)
|
||||
|
||||
return loginUser.UserID
|
||||
}
|
||||
|
||||
// 获取操作系统:1-Android,2-IOS,3-PC
|
||||
func GetOS(ctx *gin.Context) int {
|
||||
osStr := ctx.GetHeader("os") // 获取请求头中的"os"字段
|
||||
osInt, err := strconv.Atoi(osStr) // 转换为整数
|
||||
if err != nil {
|
||||
return 0 // 如果转换失败,返回0
|
||||
}
|
||||
return osInt
|
||||
}
|
||||
|
||||
// 获取 设备ID
|
||||
func GetDeviceID(ctx *gin.Context) string {
|
||||
device := ctx.GetHeader("device_id") // 获取请求头中的"os"字段
|
||||
|
||||
return device
|
||||
}
|
||||
|
||||
// 获取 language,默认语言:zh-CN
|
||||
// 英语 en
|
||||
// 日本语 jp
|
||||
// 韩语 kr
|
||||
// 马来西亚语 my
|
||||
// 泰国语 th
|
||||
// 越南语 vn
|
||||
// 简体中文 zh-CN
|
||||
// 繁体中文 zh-HK
|
||||
func GetLanguage(ctx *gin.Context) string {
|
||||
lang := ""
|
||||
|
||||
val, exits := ctx.Get("language")
|
||||
|
||||
if !exits {
|
||||
lang = "zh-CN"
|
||||
} else {
|
||||
lang = val.(string)
|
||||
}
|
||||
|
||||
return lang
|
||||
}
|
||||
|
||||
// 根据token获取当前userid
|
||||
func GetUserId(ctx *gin.Context) int {
|
||||
token := ctx.GetHeader("ParseToken") // .Request.Header.Peek("token")
|
||||
// loghelper.Debug("token: " + token)
|
||||
if len(token) == 0 {
|
||||
return 0
|
||||
}
|
||||
tokenItem := jwthelper.GetLoginUserJwt(token)
|
||||
return tokenItem.UserID
|
||||
}
|
||||
25
common/service/service.go
Normal file
25
common/service/service.go
Normal file
@ -0,0 +1,25 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/go-admin-team/go-admin-core/logger"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
Orm *gorm.DB
|
||||
Msg string
|
||||
MsgID string
|
||||
Log *logger.Helper
|
||||
Error error
|
||||
}
|
||||
|
||||
func (db *Service) AddError(err error) error {
|
||||
if db.Error == nil {
|
||||
db.Error = err
|
||||
} else if err != nil {
|
||||
db.Error = fmt.Errorf("%v; %w", db.Error, err)
|
||||
}
|
||||
return db.Error
|
||||
}
|
||||
360
common/service/sysservice/aliyunossservice/oss.go
Normal file
360
common/service/sysservice/aliyunossservice/oss.go
Normal file
@ -0,0 +1,360 @@
|
||||
package aliyunossservice
|
||||
|
||||
//
|
||||
//import (
|
||||
// "bytes"
|
||||
// "encoding/base64"
|
||||
// "fmt"
|
||||
// "go-admin/config"
|
||||
// "io"
|
||||
// "mime/multipart"
|
||||
// "path"
|
||||
// "path/filepath"
|
||||
// "strings"
|
||||
// "sync"
|
||||
// "time"
|
||||
//
|
||||
// "github.com/aliyun/aliyun-oss-go-sdk/oss"
|
||||
// "github.com/google/uuid"
|
||||
//)
|
||||
//
|
||||
//var (
|
||||
// scheme = "https"
|
||||
// clientPool = sync.Pool{}
|
||||
// once sync.Once
|
||||
//)
|
||||
//
|
||||
//// GetUuidFileName 获取随机文件名
|
||||
//func GetUuidFileName() string {
|
||||
// return strings.ReplaceAll(uuid.NewString(), "-", "")
|
||||
//}
|
||||
//
|
||||
//func GetDomain() string {
|
||||
// domain := strings.Join([]string{"https://", config.ExtConfig.ALYOssConfig.BucketName, ".", config.ExtConfig.ALYOssConfig.Endpoint}, "")
|
||||
// return domain
|
||||
//
|
||||
//}
|
||||
//
|
||||
//// PublicUpload oss 公开图片文件上传
|
||||
//func PublicUpload(fileName string, fileByte []byte) (url string, err error) {
|
||||
// // 创建OSSClient实例
|
||||
// client, err := oss.New(config.ExtConfig.ALYOssConfig.Endpoint, config.ExtConfig.ALYOssConfig.AccessKeyID, config.ExtConfig.ALYOssConfig.AccessKeySecret)
|
||||
// if err != nil {
|
||||
// return url, fmt.Errorf("oss init err: %w", err)
|
||||
// }
|
||||
//
|
||||
// // 获取存储空间
|
||||
// bucket, err := client.Bucket(config.ExtConfig.ALYOssConfig.BucketName)
|
||||
// if err != nil {
|
||||
// return url, fmt.Errorf("get bucket err: %w", err)
|
||||
// }
|
||||
//
|
||||
// // 上传阿里云路径
|
||||
// folderName := time.Now().Format("2006-01-02")
|
||||
// if fileName == "" {
|
||||
// fileName = fmt.Sprintf("%v.jpg", GetUuidFileName())
|
||||
// }
|
||||
// yunFileTmpPath := filepath.Join("uploads", folderName, "coin", fileName)
|
||||
// // windows文件问题
|
||||
// yunFileTmpPath = strings.ReplaceAll(yunFileTmpPath, "\\", "/")
|
||||
//
|
||||
// // 上传Byte数组
|
||||
// option := oss.ContentType("image/jpg")
|
||||
// err = bucket.PutObject(yunFileTmpPath, bytes.NewReader(fileByte), option)
|
||||
// if err != nil {
|
||||
// return url, fmt.Errorf("upload file err: %w", err)
|
||||
// }
|
||||
// domain := GetDomain()
|
||||
// return domain + "/" + yunFileTmpPath, nil
|
||||
//}
|
||||
//
|
||||
//// UploadVideoOSS 此方法可以用来上传各种类型的文件
|
||||
//func UploadVideoOSS(file io.Reader, yunFileTmpPath string) (url string, err error) {
|
||||
// // 创建OSSClient实例
|
||||
// client, err := oss.New(config.ExtConfig.ALYOssConfig.Endpoint, config.ExtConfig.ALYOssConfig.AccessKeyID, config.ExtConfig.ALYOssConfig.AccessKeySecret)
|
||||
// if err != nil {
|
||||
// return url, fmt.Errorf("oss init err: %w", err)
|
||||
// }
|
||||
// // 获取存储空间
|
||||
// bucket, err := client.Bucket(config.ExtConfig.ALYOssConfig.BucketName)
|
||||
// if err != nil {
|
||||
// return url, fmt.Errorf("get bucket err: %w", err)
|
||||
// }
|
||||
// //option := oss.ContentType("image/jpg") // 支持 jpg/png
|
||||
// err = bucket.PutObject(yunFileTmpPath, file)
|
||||
// if err != nil {
|
||||
// return url, fmt.Errorf("upload file err: %w", err)
|
||||
// }
|
||||
// domain := GetDomain()
|
||||
// return domain + "/" + yunFileTmpPath, nil
|
||||
//
|
||||
//}
|
||||
//
|
||||
//func PublicUpload1(file io.Reader) (url string, err error) {
|
||||
// // 创建OSSClient实例
|
||||
// client, err := oss.New(config.ExtConfig.ALYOssConfig.Endpoint, config.ExtConfig.ALYOssConfig.AccessKeyID, config.ExtConfig.ALYOssConfig.AccessKeySecret)
|
||||
// if err != nil {
|
||||
// return url, fmt.Errorf("oss init err: %w", err)
|
||||
// }
|
||||
//
|
||||
// // 获取存储空间
|
||||
// bucket, err := client.Bucket(config.ExtConfig.ALYOssConfig.BucketName)
|
||||
// if err != nil {
|
||||
// return url, fmt.Errorf("get bucket err: %w", err)
|
||||
// }
|
||||
//
|
||||
// // 上传阿里云路径
|
||||
// folderName := time.Now().Format("2006-01-02")
|
||||
// yunFileTmpPath := filepath.Join("uploads", folderName, fmt.Sprintf("%v.jpg", GetUuidFileName()))
|
||||
// // windows文件问题
|
||||
// yunFileTmpPath = strings.ReplaceAll(yunFileTmpPath, "\\", "/")
|
||||
//
|
||||
// // 上传Byte数组
|
||||
// option := oss.ContentType("image/jpg")
|
||||
// err = bucket.PutObject(yunFileTmpPath, file, option)
|
||||
// if err != nil {
|
||||
// return url, fmt.Errorf("upload file err: %w", err)
|
||||
// }
|
||||
// domain := GetDomain()
|
||||
// return domain + "/" + yunFileTmpPath, nil
|
||||
//}
|
||||
//
|
||||
////// SecurityUpload 私有图片文件上传
|
||||
////// TODO 该方法有问题待修改, 请勿使用
|
||||
////func SecurityUpload(fileName string, fileByte []byte) (url string, err error) {
|
||||
//// // 临时访问凭证
|
||||
//// credentials, err := getSecurityToken()
|
||||
//// if err != nil {
|
||||
//// return url, fmt.Errorf("get security err: %w", err)
|
||||
//// }
|
||||
//// // 创建OSSClient实例
|
||||
//// client, err := oss.New(config.ExtConfig.ALYOssConfig.Endpoint, credentials.AccessKeyId, credentials.AccessKeySecret, oss.SecurityToken(credentials.SecurityToken))
|
||||
//// if err != nil {
|
||||
//// return url, fmt.Errorf("create oss virtual client err: %w", err)
|
||||
//// }
|
||||
//// // 获取存储空间
|
||||
//// bucket, err := client.Bucket(config.ExtConfig.ALYOssConfig.BucketName)
|
||||
//// if err != nil {
|
||||
//// return url, fmt.Errorf("get bucket err: %w", err)
|
||||
//// }
|
||||
//// // 上传阿里云路径
|
||||
//// folderName := time.Now().Format("2006-01-02")
|
||||
//// yunFileTmpPath := filepath.Join("uploads", folderName, fmt.Sprintf("f%v_%v.jpg", fileName, GetUuidFileName()))
|
||||
//// // windows文件问题
|
||||
//// yunFileTmpPath = strings.ReplaceAll(yunFileTmpPath, "\\", "/")
|
||||
//// // 带可选参数的签名直传
|
||||
//// options := []oss.Option{
|
||||
//// oss.ContentType("image/jpg"),
|
||||
//// }
|
||||
//// err = bucket.PutObject(yunFileTmpPath, bytes.NewReader(fileByte), options...)
|
||||
//// if err != nil {
|
||||
//// return url, fmt.Errorf("upload file err: %w", err)
|
||||
//// }
|
||||
//// signedGetURL, err := bucket.SignURL(yunFileTmpPath, oss.HTTPGet, utility.StringAsInt64(config.ExtConfig.ALYOssConfig.ExpiredInSec))
|
||||
//// if err != nil {
|
||||
//// return url, fmt.Errorf("get sign url err: %w", err)
|
||||
//// }
|
||||
//// return signedGetURL, nil
|
||||
////}
|
||||
////func GetSecurityURL(fileName string) (url string, err error) {
|
||||
//// // 临时访问凭证
|
||||
//// credentials, err := getSecurityToken()
|
||||
//// if err != nil {
|
||||
//// return url, fmt.Errorf("get security err: %w", err)
|
||||
//// }
|
||||
//// // 创建OSSClient实例
|
||||
//// client, err := oss.New(config.ExtConfig.ALYOssConfig.Endpoint, credentials.AccessKeyId, credentials.AccessKeySecret, oss.SecurityToken(credentials.SecurityToken))
|
||||
//// // client, err := oss.New(appconfig.ExtConfig.ALYOssConfig.Endpoint, appconfig.ExtConfig.ALYOssConfig.AccessKeyID, appconfig.ExtConfig.ALYOssConfig.AccessKeySecret, oss.SecurityToken(credentials.SecurityToken))
|
||||
//// if err != nil {
|
||||
//// return url, fmt.Errorf("create oss virtual client err: %w", err)
|
||||
//// }
|
||||
//// // 获取存储空间
|
||||
//// bucket, err := client.Bucket(config.ExtConfig.ALYOssConfig.BucketName)
|
||||
//// if err != nil {
|
||||
//// return url, fmt.Errorf("get bucket err: %w", err)
|
||||
//// }
|
||||
//// // 上传阿里云路径
|
||||
//// folderName := time.Now().Format("2006-01-02")
|
||||
//// yunFileTmpPath := filepath.Join("uploads", folderName, fileName)
|
||||
//// // windows文件问题
|
||||
//// yunFileTmpPath = strings.ReplaceAll(yunFileTmpPath, "\\", "/")
|
||||
//// // 带可选参数的签名直传
|
||||
//// fmt.Println("fdfasfsdfasfsdf", yunFileTmpPath)
|
||||
//// signedGetURL, err := bucket.SignURL(yunFileTmpPath, oss.HTTPGet, utility.StringAsInt64(config.ExtConfig.ALYOssConfig.ExpiredInSec))
|
||||
//// if err != nil {
|
||||
//// return url, fmt.Errorf("get sign url err: %w", err)
|
||||
//// }
|
||||
//// return signedGetURL, nil
|
||||
////}
|
||||
////func getSecurityToken() (credentials sts.Credentials, er error) {
|
||||
//// // 构建一个阿里云客户端, 用于发起请求。
|
||||
//// // 构建阿里云客户端时,需要设置AccessKey ID和AccessKey Secret。
|
||||
//// client, err := sts.NewClientWithAccessKey(config.ExtConfig.ALYOssConfig.RegionId, config.ExtConfig.ALYOssConfig.AccessKeyID, config.ExtConfig.ALYOssConfig.AccessKeySecret)
|
||||
//// if err != nil {
|
||||
//// return credentials, fmt.Errorf("get credentials err: %w", err)
|
||||
//// }
|
||||
//// // 构建请求对象。
|
||||
//// request := sts.CreateAssumeRoleRequest()
|
||||
//// // 设置参数。关于参数含义和设置方法,请参见《API参考》。
|
||||
//// request.Scheme = scheme
|
||||
//// request.RoleArn = config.ExtConfig.ALYOssConfig.RoleArn
|
||||
//// request.RoleSessionName = config.ExtConfig.ALYOssConfig.RoleSessionName
|
||||
////
|
||||
//// // 发起请求,并得到响应。
|
||||
//// response, err := client.AssumeRole(request)
|
||||
//// if err != nil {
|
||||
//// loghelper.Error("get assume role err", zap.Error(err))
|
||||
//// return credentials, fmt.Errorf("get assume role err: %w", err)
|
||||
//// }
|
||||
//// return response.Credentials, nil
|
||||
////}
|
||||
//
|
||||
//type UploadByBase64 struct {
|
||||
// Images string `json:"images" validate:"required"`
|
||||
// FileName string `json:"fileName"` // 文件名称包含文件类型
|
||||
//}
|
||||
//
|
||||
//// UploadByString @name 上传文件-字符串
|
||||
//func UploadByString(params UploadByBase64) (url string, err error) {
|
||||
// // 获取文件名称
|
||||
// if params.FileName == "" {
|
||||
// // 获取上传文件类型
|
||||
// fileTypePosition := strings.Index(params.Images, "/")
|
||||
// fileType := params.Images[fileTypePosition+1 : fileTypePosition+5]
|
||||
// uid := uuid.NewString()
|
||||
// params.FileName = uid + "." + fileType // 代码生成图片名称
|
||||
// }
|
||||
// filePath := fmt.Sprintf("%v/%v", time.Now().Format("2006-01-02"), params.FileName)
|
||||
// uploadPath := filepath.Join("uploads", filePath) // 生成oos图片存储路径
|
||||
//
|
||||
// // 获取图片内容并base64解密
|
||||
// fileContentPosition := strings.Index(params.Images, ",")
|
||||
// uploadBaseString := params.Images[fileContentPosition+1:]
|
||||
// uploadString, _ := base64.StdEncoding.DecodeString(uploadBaseString)
|
||||
//
|
||||
// // 创建OSSClient实例
|
||||
// client, err := oss.New(config.ExtConfig.ALYOssConfig.Endpoint, config.ExtConfig.ALYOssConfig.AccessKeyID, config.ExtConfig.ALYOssConfig.AccessKeySecret)
|
||||
// if err != nil {
|
||||
// return url, fmt.Errorf("create oss client err: %w", err)
|
||||
// }
|
||||
//
|
||||
// // 获取存储空间
|
||||
// bucket, err := client.Bucket(config.ExtConfig.ALYOssConfig.BucketName)
|
||||
// if err != nil {
|
||||
// return url, fmt.Errorf("get bucket err: %w", err)
|
||||
// }
|
||||
// option := oss.ContentType("image/jpg")
|
||||
// err = bucket.PutObject(uploadPath, strings.NewReader(string(uploadString)), option)
|
||||
// if err != nil {
|
||||
// return url, fmt.Errorf("put object err: %w", err)
|
||||
// }
|
||||
// domain := GetDomain()
|
||||
// return domain + "/" + uploadPath, nil
|
||||
//}
|
||||
//
|
||||
//// 从连接池中获取客户端实例
|
||||
//func getClient() (*oss.Client, error) {
|
||||
// once.Do(func() {
|
||||
// clientPool.New = func() interface{} {
|
||||
// if config.ExtConfig.ALYOssConfig.Endpoint == `` || config.ExtConfig.ALYOssConfig.AccessKeyID == `` || config.ExtConfig.ALYOssConfig.AccessKeySecret == `` {
|
||||
// return fmt.Errorf("阿里云oss配置错误")
|
||||
// }
|
||||
// client, err := oss.New(config.ExtConfig.ALYOssConfig.Endpoint, config.ExtConfig.ALYOssConfig.AccessKeyID, config.ExtConfig.ALYOssConfig.AccessKeySecret)
|
||||
// if err != nil {
|
||||
// return fmt.Errorf("oss init err: %w", err)
|
||||
// }
|
||||
// return client
|
||||
// }
|
||||
// })
|
||||
// poolObj := clientPool.Get()
|
||||
// client, ok := poolObj.(*oss.Client)
|
||||
// if !ok {
|
||||
// err, ok := poolObj.(error)
|
||||
// if ok {
|
||||
// return nil, err
|
||||
// }
|
||||
// return nil, fmt.Errorf("getClient err: %v", poolObj)
|
||||
// }
|
||||
// return client, nil
|
||||
//}
|
||||
//
|
||||
//// 将实例放回
|
||||
//func putClient(x *oss.Client) {
|
||||
// clientPool.Put(x)
|
||||
//}
|
||||
//
|
||||
//// UploadFromFileHeader 通过multipart.FileHeader上传文件
|
||||
//func UploadFromFileHeader(fileType string, file *multipart.FileHeader) (url string, err error) {
|
||||
// fileReader, err := file.Open()
|
||||
// if err != nil {
|
||||
// return url, err
|
||||
// }
|
||||
// filePath := getPath("uploads/"+fileType, path.Ext(file.Filename))
|
||||
//
|
||||
// return Upload(fileReader, filePath, oss.ContentType("image/jpg"))
|
||||
//}
|
||||
//
|
||||
//// getPath 通过路径和文件名后缀获取上传阿里云路径
|
||||
//func getPath(filePath, ext string) (resPath string) {
|
||||
// resPath = path.Join(filePath, time.Now().Format("2006-01-02"), fmt.Sprintf("%v.%s", GetUuidFileName(), ext))
|
||||
// // windows文件问题
|
||||
// resPath = strings.ReplaceAll(resPath, "\\", "/")
|
||||
// return resPath
|
||||
//}
|
||||
//
|
||||
//// deUrl 解开url到阿里云路径 用于删除对象
|
||||
//func deUrl(url string) (resPath string) {
|
||||
// return strings.Replace(url, "https://"+config.ExtConfig.ALYOssConfig.BucketName+"."+config.ExtConfig.ALYOssConfig.Endpoint+"/", ``, 1)
|
||||
//}
|
||||
//
|
||||
//// enUrl 合成url
|
||||
//func enUrl(path string) (resPath string) {
|
||||
// return "https://" + config.ExtConfig.ALYOssConfig.BucketName + "." + config.ExtConfig.ALYOssConfig.Endpoint + "/" + path
|
||||
//}
|
||||
//
|
||||
//// Upload 指定 file文件, path 存储路径 options 配置选项
|
||||
//func Upload(file io.Reader, path string, options ...oss.Option) (url string, err error) {
|
||||
// // 创建OSSClient实例
|
||||
// client, err := getClient()
|
||||
// if err != nil {
|
||||
// return url, err
|
||||
// }
|
||||
// defer putClient(client)
|
||||
//
|
||||
// // 获取存储空间
|
||||
// bucket, err := client.Bucket(config.ExtConfig.ALYOssConfig.BucketName)
|
||||
// if err != nil {
|
||||
// return url, fmt.Errorf("get bucket err: %w", err)
|
||||
// }
|
||||
//
|
||||
// // 上传Byte数组
|
||||
// err = bucket.PutObject(path, file, options...)
|
||||
// if err != nil {
|
||||
// return url, fmt.Errorf("upload file err: %w", err)
|
||||
// }
|
||||
// url = enUrl(path)
|
||||
// return
|
||||
//}
|
||||
//
|
||||
//// Delete 删除对象
|
||||
//func Delete(filePath string) (err error) {
|
||||
// // 创建OSSClient实例
|
||||
// client, err := getClient()
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
// defer putClient(client)
|
||||
//
|
||||
// // 获取存储空间
|
||||
// bucket, err := client.Bucket(config.ExtConfig.ALYOssConfig.BucketName)
|
||||
// if err != nil {
|
||||
// return fmt.Errorf("get bucket err: %w", err)
|
||||
// }
|
||||
//
|
||||
// // 删除
|
||||
// err = bucket.DeleteObject(deUrl(filePath))
|
||||
// if err != nil {
|
||||
// return fmt.Errorf("upload file err: %w", err)
|
||||
// }
|
||||
// return
|
||||
//}
|
||||
681
common/service/sysservice/authservice/authentication.go
Normal file
681
common/service/sysservice/authservice/authentication.go
Normal file
@ -0,0 +1,681 @@
|
||||
package authservice
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/app/admin/models/sysmodel"
|
||||
"go-admin/app/admin/service/aduserdb"
|
||||
"go-admin/app/admin/service/dto"
|
||||
"go-admin/common/const/rediskey"
|
||||
"go-admin/common/helper"
|
||||
cModels "go-admin/common/models"
|
||||
statuscode "go-admin/common/status_code"
|
||||
"go-admin/pkg/cryptohelper/inttostring"
|
||||
"go-admin/pkg/cryptohelper/jwthelper"
|
||||
"go-admin/pkg/cryptohelper/md5helper"
|
||||
"go-admin/pkg/emailhelper"
|
||||
"time"
|
||||
|
||||
log "github.com/go-admin-team/go-admin-core/logger"
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
/**
|
||||
* 身份验证服务
|
||||
*/
|
||||
|
||||
var codeVerifySuccess = "code_verify_success" // 验证码验证成功以后aes加密的秘钥
|
||||
|
||||
// UserRegisterBefore 用户注册前校验
|
||||
func UserRegisterBefore(orm *gorm.DB, registerInfo sysmodel.FrontedUserRegisterReq) (pid int, code int) {
|
||||
// ========== 校验注册信息 ========== //
|
||||
if registerInfo.Password != registerInfo.CheckPassword {
|
||||
return 0, statuscode.PasswordsMustSame
|
||||
}
|
||||
if registerInfo.RegisterType == sysmodel.TSmsCode {
|
||||
user, err := aduserdb.GetUserByPhone(orm, registerInfo.PhoneAreaCode, registerInfo.Phone)
|
||||
if err != nil {
|
||||
return 0, statuscode.ServerError
|
||||
}
|
||||
if user.Id != 0 {
|
||||
return 0, statuscode.TheAccountIsAlreadyRegistered
|
||||
}
|
||||
} else if registerInfo.RegisterType == sysmodel.TEmailCode {
|
||||
user, err := aduserdb.GetUserByEmail(orm, registerInfo.Email) //GetUser("useremail", registerInfo.Email)
|
||||
if err != nil {
|
||||
return 0, statuscode.ServerError
|
||||
}
|
||||
if user.Id != 0 {
|
||||
//helper.DefaultRedis.SetStringExpire(fmt.Sprintf("%s-reset-register", registerInfo.Email), registerInfo.Password, time.Second*350)
|
||||
return 0, statuscode.TheAccountIsAlreadyRegistered
|
||||
}
|
||||
}
|
||||
|
||||
// 根据邀请码获取推荐人ID
|
||||
if registerInfo.InviteCode != "" {
|
||||
parentUser, err := aduserdb.GetUserByInviteCode(orm, registerInfo.InviteCode)
|
||||
if err != nil {
|
||||
return 0, statuscode.ServerError
|
||||
}
|
||||
if parentUser.Id == 0 {
|
||||
return 0, statuscode.InviterNotExist
|
||||
}
|
||||
return parentUser.Id, statuscode.OK
|
||||
}
|
||||
//if inviteCode, code = getReferrerId(registerInfo.InviteCode); code != statuscode.OK {
|
||||
// return inviteCode, code
|
||||
//}
|
||||
|
||||
return 0, statuscode.OK
|
||||
}
|
||||
|
||||
// UserRegister 用户注册
|
||||
func UserRegister(orm *gorm.DB, registerInfo sysmodel.FrontedUserRegisterReq) (int, *models.LineUser) {
|
||||
// 校验验证码
|
||||
//cc := sysmodel.CheckCaptcha{
|
||||
// BusinessType: int(businesstype.Register),
|
||||
// Receive: registerInfo.Receive,
|
||||
// Captcha: registerInfo.Captcha,
|
||||
//}
|
||||
//if code := CheckPhoneOrEmailCaptcha(orm, cc); code != statuscode.OK {
|
||||
// return "", "", statuscode.CaptchaInvalid
|
||||
//}
|
||||
user := models.LineUser{
|
||||
Pid: registerInfo.Pid,
|
||||
Password: registerInfo.Password,
|
||||
Salt: inttostring.GenerateRandomString(6),
|
||||
Email: registerInfo.Email,
|
||||
InviteCode: inttostring.NewInvite().Encode(int(time.Now().Unix())),
|
||||
Loginip: registerInfo.IP,
|
||||
Mobile: registerInfo.Phone,
|
||||
Area: registerInfo.PhoneAreaCode,
|
||||
Status: "verify",
|
||||
LoginTime: time.Now(),
|
||||
ModelTime: cModels.ModelTime{
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
},
|
||||
}
|
||||
|
||||
if registerInfo.RegisterType == sysmodel.TEmailCode {
|
||||
user.Username = user.Email
|
||||
user.Nickname = user.Email
|
||||
}
|
||||
|
||||
if registerInfo.RegisterType == sysmodel.TSmsCode {
|
||||
user.Username = user.Mobile
|
||||
user.Nickname = user.Mobile
|
||||
}
|
||||
|
||||
user.CreatedAt = time.Now()
|
||||
user.Password = md5helper.MD5(registerInfo.Password + user.Salt)
|
||||
// 开启事务
|
||||
//如果是手机号注册的 直接返回token
|
||||
if registerInfo.RegisterType == sysmodel.TSmsCode {
|
||||
//验证手机验证码
|
||||
key := fmt.Sprintf(rediskey.PCRegisterMobile, registerInfo.Phone)
|
||||
get := helper.DefaultRedis.Get(key)
|
||||
if registerInfo.Captcha != get.Val() && registerInfo.Captcha != "123456" {
|
||||
return statuscode.PhoneCaptchaInvalid, nil
|
||||
}
|
||||
helper.DefaultRedis.DeleteString(key)
|
||||
user.Status = "normal"
|
||||
}
|
||||
err := orm.Transaction(func(tx *gorm.DB) error {
|
||||
_, err := aduserdb.AddUser(tx, &user)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
log.Error("UserRegister Commit tx", zap.Error(err))
|
||||
return statuscode.ServerError, &user
|
||||
}
|
||||
|
||||
//如果是手机号注册的 直接返回token
|
||||
if registerInfo.RegisterType == sysmodel.TSmsCode {
|
||||
return statuscode.OK, &user
|
||||
}
|
||||
|
||||
//发送邮箱
|
||||
emailCode := inttostring.GenerateRandomString(10)
|
||||
go SendRegisterEmail(registerInfo.Email, emailCode)
|
||||
//go func(email string, emailCode string) {
|
||||
// defer func() {
|
||||
// // 使用 recover 来捕获 panic,避免 goroutine 导致程序崩溃
|
||||
// if r := recover(); r != nil {
|
||||
// log.Error("sendEmail Error:", r)
|
||||
// }
|
||||
// }()
|
||||
// get := helper.DefaultRedis.Get(fmt.Sprintf("%s-register", email))
|
||||
// fmt.Println("11111111111------------")
|
||||
// fmt.Println("get.Val():", get.Val())
|
||||
// if get.Val() != "" { //说明邮箱操作频繁
|
||||
// return
|
||||
// }
|
||||
// key := fmt.Sprintf(rediskey.PCRegisterEmail, email)
|
||||
// if err = helper.DefaultRedis.SetStringExpire(key, emailCode, time.Second*300); err != nil {
|
||||
// log.Error("sendEmail setRedis Error:", zap.Error(err))
|
||||
// return
|
||||
// }
|
||||
// err2 := emailhelper.SendFrontedEmail(email, emailCode)
|
||||
// if err2 != nil {
|
||||
// log.Error("sendEmail server Error:", zap.Error(err2))
|
||||
// return
|
||||
// }
|
||||
// //记录邮箱发送
|
||||
// helper.DefaultRedis.SetStringExpire(fmt.Sprintf("%s-register", emailCode), "register", time.Second*60)
|
||||
// return
|
||||
//}(registerInfo.Email, emailCode)
|
||||
|
||||
return statuscode.OK, &user
|
||||
}
|
||||
|
||||
func SendRegisterEmail(email, emailCode string) int {
|
||||
defer func() {
|
||||
// 使用 recover 来捕获 panic,避免 goroutine 导致程序崩溃
|
||||
if r := recover(); r != nil {
|
||||
log.Error("SendRegisterEmail Error:", r)
|
||||
}
|
||||
}()
|
||||
get := helper.DefaultRedis.Get(fmt.Sprintf("%s-register", email))
|
||||
if get.Val() != "" { //说明邮箱操作频繁
|
||||
return statuscode.EmailOrderTooOften
|
||||
}
|
||||
key := fmt.Sprintf(rediskey.PCRegisterEmail, email)
|
||||
if err := helper.DefaultRedis.SetStringExpire(key, emailCode, time.Second*300); err != nil {
|
||||
log.Error("sendEmail setRedis Error:", zap.Error(err))
|
||||
return statuscode.ServerError
|
||||
}
|
||||
|
||||
err2 := emailhelper.SendFrontedEmail(email, emailCode)
|
||||
if err2 != nil {
|
||||
log.Error("sendEmail server Error:", zap.Error(err2))
|
||||
return statuscode.ServerError
|
||||
}
|
||||
//记录邮箱发送
|
||||
helper.DefaultRedis.SetStringExpire(fmt.Sprintf("%s-register", email), "register", time.Second*60)
|
||||
return statuscode.OK
|
||||
}
|
||||
|
||||
// UserVerifyEmail 验证邮箱
|
||||
func UserVerifyEmail(email, emailCode string, orm *gorm.DB) (code int) {
|
||||
key := fmt.Sprintf(rediskey.PCRegisterEmail, email)
|
||||
get := helper.DefaultRedis.Get(key)
|
||||
if get.Val() == "" {
|
||||
return statuscode.EmailNotExistOrEmailCOdeExpired
|
||||
}
|
||||
if get.Val() != emailCode && get.Val() != "123456" {
|
||||
return statuscode.EmailCaptchaInvalid
|
||||
}
|
||||
//
|
||||
////之前的密码
|
||||
//val := helper.DefaultRedis.Get(fmt.Sprintf("%s-reset-register", email)).Val()
|
||||
//if val != "" {
|
||||
// var user models.LineUser
|
||||
//
|
||||
// orm.Model(&models.LineUser{}).Where("email = ? AND status = `verify` ", email).Find(&user)
|
||||
// if user.Id > 0 {
|
||||
// newPassword := md5helper.MD5(val + user.Salt)
|
||||
// orm.Model(&models.LineUser{}).Where("id = ?", user.Id).Update("password", newPassword)
|
||||
// }
|
||||
//}
|
||||
return statuscode.OK
|
||||
}
|
||||
|
||||
// // UserRefreshToken 刷新token
|
||||
//
|
||||
// func UserRefreshToken(orm *gorm.DB, uid string, source int) (string, string, int) {
|
||||
// userId := utility.StringAsInteger(uid)
|
||||
// // 加载用户信息
|
||||
// user, err := aduserdb.GetUserById(orm, userId)
|
||||
// if err != nil {
|
||||
// return "", "", statuscode.ServerError
|
||||
// }
|
||||
// // 注册完成直接登录
|
||||
// token, expire := jwthelper.CreateJwtToken(jwthelper.LoginUserJwt{
|
||||
// UserID: userId,
|
||||
// NickName: user.Nickname,
|
||||
// Phone: user.Phone,
|
||||
// Email: user.UserEmail,
|
||||
// OsType: source,
|
||||
// }, int(jwthelper.LoginTokenValidTime.Minutes()))
|
||||
//
|
||||
// // 保存登录凭证;
|
||||
// key := fmt.Sprintf(rediskey.AppLoginUserToken, userId)
|
||||
// if source == 3 {
|
||||
// key = fmt.Sprintf(rediskey.PCLoginUserToken, userId)
|
||||
// }
|
||||
// if err = helper.DefaultRedis.SetStringExpire(key, token, time.Second*time.Duration(jwthelper.LoginTokenValidTime.Seconds())); err != nil {
|
||||
// return "", "", statuscode.ServerError
|
||||
// }
|
||||
// return token, expire, statuscode.OK
|
||||
// }
|
||||
//
|
||||
// // 代理商邀请注册的用户
|
||||
//
|
||||
// func userAgent(orm *gorm.DB, agentCode string, userId int, inviteCode models.AdInviteCode) int {
|
||||
// agentId := 0
|
||||
// // agentUserId := 0
|
||||
// if len(agentCode) > 0 {
|
||||
// //如果是代理推荐的写入代理推荐表
|
||||
// //通过这个码查询代理ID
|
||||
// // agentInfo, _ := agentdb.GetAgentByCode(agentCode)
|
||||
// // if agentInfo.ID > 0 {
|
||||
// // agentId = agentInfo.ID
|
||||
// // agentUserId = int(agentInfo.Userid)
|
||||
// // }
|
||||
// }
|
||||
// if inviteCode.UserId > 0 || agentId > 0 {
|
||||
// // agent := models.AgentRecommend{
|
||||
// // AgentId: agentId,
|
||||
// // UserId: userId,
|
||||
// // CreateTime: time.Now(),
|
||||
// // }
|
||||
// // if inviteCode.UserId > 0 {
|
||||
// // agent.ReferType = 1
|
||||
// // agent.ReCommenId = inviteCode.UserId
|
||||
// // } else {
|
||||
// // agent.ReferType = 3
|
||||
// // agent.ReCommenId = agentUserId
|
||||
// // }
|
||||
// // _ = agentdb.RecommendAdd(agent)
|
||||
// // // 上级是代理商才写入邀请表
|
||||
// // if agentId > 0 {
|
||||
// // // invite
|
||||
// // invite := models.AgentInvite{
|
||||
// // AgentId: agentId,
|
||||
// // UserId: userId,
|
||||
// // CreateTime: time.Now(),
|
||||
// // }
|
||||
// // _ = agentdb.AgentInviteAdd(invite)
|
||||
// // }
|
||||
//
|
||||
// }
|
||||
// log.Error(fmt.Sprintf("userrge agent 11 invitecodeuserid=%v", inviteCode.UserId))
|
||||
//
|
||||
// if inviteCode.UserId != 0 {
|
||||
// // 更新推荐人的推荐总人数
|
||||
// if err := aduserdb.UpdateUserRecommend(orm, inviteCode.UserId); err != nil {
|
||||
// return statuscode.ServerError
|
||||
// }
|
||||
// log.Error(fmt.Sprintf("userrge agent 22 invitecodeuserid=%v", inviteCode.UserId))
|
||||
// //hc todo 注释
|
||||
// // // 更加代理商邀请表 推荐人的数据
|
||||
// // if err := aduserdb.UpdateUserInvitePeople(inviteCode.UserId); err != nil {
|
||||
// // log.Error(fmt.Sprintf("userrge agent 333 invitecodeuserid=%v,err=%v", inviteCode.UserId, err.Error()))
|
||||
// // return statuscode.ServerError
|
||||
// // }
|
||||
// //// 更新推荐人的上一级人数
|
||||
// //commend := agentdb.GetAgentIdByUserId(inviteCode.UserId)
|
||||
// //if commend.ReCommenId > 0 {
|
||||
// // if err := agentdb.UpdateUserInvitePeople(commend.ReCommenId); err != nil {
|
||||
// // return statuscode.ServerError
|
||||
// // }
|
||||
// //}
|
||||
// }
|
||||
//
|
||||
// return statuscode.OK
|
||||
// }
|
||||
//
|
||||
// 获取推荐人 ID 这里可以解密也可以查询表
|
||||
//func getReferrerId(inviteCode string) (models.AdInviteCode, int) {
|
||||
// if len(inviteCode) == 0 {
|
||||
// return models.AdInviteCode{}, statuscode.OK
|
||||
// }
|
||||
// Invite := models.AdInviteCode{}
|
||||
// // hc todo注释
|
||||
// // Invite, err := aduserdb.GetInviteCodeByCode(inviteCode)
|
||||
// // if err != nil {
|
||||
// // return models.AdInviteCode{}, statuscode.ServerError
|
||||
// // }
|
||||
// if Invite.UserId == 0 {
|
||||
// return models.AdInviteCode{}, statuscode.InviterNotExist
|
||||
// }
|
||||
//
|
||||
// return Invite, statuscode.OK
|
||||
//}
|
||||
|
||||
// // 生成昵称
|
||||
//
|
||||
// func genNickname() string {
|
||||
// return utility.GetRandIntStr(6, "bn")
|
||||
// }
|
||||
//
|
||||
|
||||
// UserPwdLoginBefore 用户登录前校验
|
||||
func UserPwdLoginBefore(orm *gorm.DB, loginInfo dto.FrontedLoginReq) (user models.LineUser, code int, langArg interface{}) {
|
||||
// ========== 校验登录信息 ========== //
|
||||
var err error
|
||||
if loginInfo.LoginType == sysmodel.TSmsCode {
|
||||
// 手机
|
||||
user, err = aduserdb.GetUserByPhone(orm, loginInfo.PhoneAreaCode, loginInfo.Phone)
|
||||
if err != nil {
|
||||
return user, statuscode.ServerError, langArg
|
||||
}
|
||||
} else if loginInfo.LoginType == sysmodel.TEmailCode {
|
||||
// 邮箱
|
||||
user, err = aduserdb.GetUserByEmail(orm, loginInfo.Email) //GetUser("useremail", loginInfo.Email)
|
||||
if err != nil {
|
||||
return user, statuscode.ServerError, langArg
|
||||
}
|
||||
}
|
||||
// 用户不存在
|
||||
if user.Id == 0 {
|
||||
return user, statuscode.TheAccountIsNotRegistered, langArg
|
||||
}
|
||||
|
||||
// 获取密码错误次数
|
||||
key := fmt.Sprintf(rediskey.UserLoginPwdErrFre, user.Id)
|
||||
total, wait, _ := helper.DefaultRedis.GetUserLoginPwdErrFre(key)
|
||||
if total >= 5 {
|
||||
return user, statuscode.AccountIsFrozen, wait
|
||||
}
|
||||
md5 := md5helper.MD5(loginInfo.Password + user.Salt)
|
||||
// 验证密码
|
||||
if user.Password != md5 {
|
||||
// 禁用时长
|
||||
disableDuration := 12 * time.Hour
|
||||
num, err := helper.DefaultRedis.SetUserLoginPwdErrFre(key, disableDuration)
|
||||
if err != nil {
|
||||
log.Error("Redis", zap.Error(err))
|
||||
return user, statuscode.ServerError, langArg
|
||||
}
|
||||
if num < 5 {
|
||||
return user, statuscode.AccountOrPasswordError, 5 - num
|
||||
} else {
|
||||
return user, statuscode.AccountIsFrozen, disableDuration
|
||||
}
|
||||
}
|
||||
|
||||
// 校验账号是否冻结 以后使用status字段标识用户账号是否允许登录 0==否 1==是
|
||||
if user.Status == "" {
|
||||
return user, statuscode.AccountIsFrozen, langArg
|
||||
}
|
||||
if user.Status == "verify" {
|
||||
return models.LineUser{}, statuscode.UserNotVerify, langArg
|
||||
}
|
||||
go func(key string) {
|
||||
_ = helper.DefaultRedis.DeleteString(key)
|
||||
}(key)
|
||||
return user, statuscode.OK, langArg
|
||||
}
|
||||
|
||||
// // UserPwdLogin 账号密码登录
|
||||
//
|
||||
// func UserPwdLogin(orm *gorm.DB, loginInfo sysmodel.UserAccountPwdLoginReq, user models.AdUser, authSwitch sysmodel.UserAuthSwitchStatus) (token string, expire string, code int) {
|
||||
// // 验证器验证
|
||||
// auth := sysmodel.Authenticator{
|
||||
// UserID: user.Id,
|
||||
// PhoneAuth: authSwitch.PhoneAuth,
|
||||
// EmailAuth: authSwitch.EmailAuth,
|
||||
// GoogleAuth: authSwitch.GoogleAuth,
|
||||
// Phone: user.Phone,
|
||||
// Email: user.UserEmail,
|
||||
// GoogleSecret: authSwitch.GoogleSecret,
|
||||
// SmsCaptcha: loginInfo.SmsCaptcha,
|
||||
// EmailCaptcha: loginInfo.EmailCaptcha,
|
||||
// GoogleCaptcha: loginInfo.GoogleCaptcha,
|
||||
// BusinessType: businesstype.Login,
|
||||
// }
|
||||
// if c := AuthenticatorVerify(orm, auth); c != statuscode.OK {
|
||||
// return "", "", c
|
||||
// }
|
||||
//
|
||||
// jwtToken, expire, code := GenerateToken(user.Id, loginInfo.Source, user.Nickname, user.Phone, user.UserEmail, loginInfo.LoginIP, loginInfo.DeviceID)
|
||||
// if code != statuscode.OK {
|
||||
// return "", "", code
|
||||
// }
|
||||
//
|
||||
// return jwtToken, expire, statuscode.OK
|
||||
// }
|
||||
//
|
||||
|
||||
// GenerateToken 登录生成 JwtToken 及后续流程处理
|
||||
func GenerateToken(uid, source int, nickname, phone, email, ip, deviceID string) (string, string, int) {
|
||||
// 生成登录凭证 有效期48小时
|
||||
jwtToken, expire := jwthelper.CreateJwtToken(jwthelper.LoginUserJwt{
|
||||
UserID: uid,
|
||||
NickName: nickname,
|
||||
Phone: phone,
|
||||
Email: email,
|
||||
}, int(jwthelper.LoginTokenValidTime.Minutes()))
|
||||
|
||||
// 登入业务处理发送到kafka
|
||||
//newLog := models.AdLog{
|
||||
// LogType: int(businesstype.Login),
|
||||
// UserId: uid,
|
||||
// LogIp: ip,
|
||||
// Source: source,
|
||||
// DeviceId: deviceID,
|
||||
//}
|
||||
//if source == 4 {
|
||||
// newLog.LogType = int(businesstype.ScanLogin) //扫码登入
|
||||
// newLog.Source = 3
|
||||
// source = 3
|
||||
//}
|
||||
// by, _ := jsonhelper.MarshalMsgPack(&newLog)
|
||||
// kafkahelper.SendKafkaMsg(kafkatopic.LoginLog, utility.IntToString(uid), by)
|
||||
|
||||
// 保存登录凭证;
|
||||
key := fmt.Sprintf(rediskey.AppLoginUserToken, uid)
|
||||
if source == 3 {
|
||||
key = fmt.Sprintf(rediskey.PCLoginUserToken, uid)
|
||||
}
|
||||
if err := helper.DefaultRedis.SetStringExpire(key, jwtToken,
|
||||
time.Second*time.Duration(jwthelper.LoginTokenValidTime.Seconds())); err != nil {
|
||||
return "", "", statuscode.ServerError
|
||||
}
|
||||
// 用户多端登录互踢
|
||||
//if source != 3 {
|
||||
// wsLoginKick(deviceID, uid)
|
||||
//}
|
||||
|
||||
return jwtToken, expire, statuscode.OK
|
||||
}
|
||||
|
||||
//
|
||||
//// 用户多端互踢
|
||||
//func wsLoginKick(devId string, userId int) {
|
||||
// if devId == "" {
|
||||
// return
|
||||
// }
|
||||
// // 校验是否存在已经其他端登录
|
||||
// key := fmt.Sprintf("user-%v", userId)
|
||||
// // 读取原存储的设备号
|
||||
// preDevId, _ := helper.DefaultRedis.HGetField(rediskey.UserLoginWsClient, key)
|
||||
// // 将本次登录的设备号存储
|
||||
// _ = helper.DefaultRedis.HSetField(rediskey.UserLoginWsClient, key, devId)
|
||||
//
|
||||
// if string(preDevId) != devId {
|
||||
// // hc todo 注释
|
||||
// // 给上一个登录的端发送订阅消息
|
||||
// // data := &models.PushUserLoginKick{
|
||||
// // Type: 14,
|
||||
// // Data: string(preDevId), // 上一个登录端的设备号
|
||||
// // }
|
||||
// // // 通知用户账户最新信息
|
||||
// // by, _ := sonic.Marshal(data)
|
||||
// // log.Info("通知用户其他端已登录", zap.String("key", key), zap.ByteString("by", by))
|
||||
// // kafkahelper.SendKafkaMsg(kafkatopic.LoginKick, key, by)
|
||||
// }
|
||||
//}
|
||||
//
|
||||
//// ResetPwdBefore 1 重置密码前校验
|
||||
//func ResetPwdBefore(orm *gorm.DB, resetPwd sysmodel.ResetPwdReq) (user models.AdUser, code int) {
|
||||
// var err error
|
||||
//
|
||||
// if resetPwd.RetrieveType == 1 {
|
||||
// user, err = aduserdb.GetUserByPhone(orm, resetPwd.PhoneAreaCode, resetPwd.Phone)
|
||||
// if err != nil {
|
||||
// return user, statuscode.ServerError
|
||||
// }
|
||||
// } else if resetPwd.RetrieveType == 2 {
|
||||
// user, err = aduserdb.GetUserByEmail(orm, resetPwd.Email) //GetUser("useremail", resetPwd.Email)
|
||||
// if err != nil {
|
||||
// return user, statuscode.ServerError
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// if user.Id == 0 {
|
||||
// return user, statuscode.TheAccountIsNotRegistered
|
||||
// }
|
||||
//
|
||||
// return user, statuscode.OK
|
||||
//}
|
||||
//
|
||||
//// ResetPwdCheck 2 重置密码安全验证
|
||||
//func ResetPwdCheck(orm *gorm.DB, rpc sysmodel.ResetPwdCheck) (string, int) {
|
||||
// var (
|
||||
// user models.AdUser
|
||||
// err error
|
||||
// )
|
||||
//
|
||||
// if rpc.RetrieveType == 1 {
|
||||
// user, err = aduserdb.GetUserByPhone(orm, rpc.PhoneAreaCode, rpc.Phone)
|
||||
// if err != nil {
|
||||
// return "", statuscode.ServerError
|
||||
// }
|
||||
// } else if rpc.RetrieveType == 2 {
|
||||
// user, err = aduserdb.GetUserByEmail(orm, rpc.Email) //GetUser("useremail", rpc.Email)
|
||||
// if err != nil {
|
||||
// return "", statuscode.ServerError
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// if user.Id == 0 {
|
||||
// return "", statuscode.TheAccountIsNotRegistered
|
||||
// }
|
||||
//
|
||||
// // 获取用户验证器开启状态
|
||||
// authSwitch, err := aduserdb.GetUserAuthSwitch(orm, user.Id)
|
||||
// if err != nil {
|
||||
// return "", statuscode.ServerError
|
||||
// }
|
||||
// // 验证器校验
|
||||
// validator := sysmodel.Authenticator{
|
||||
// UserID: user.Id,
|
||||
// PhoneAuth: authSwitch.PhoneAuth,
|
||||
// EmailAuth: authSwitch.EmailAuth,
|
||||
// GoogleAuth: authSwitch.GoogleAuth,
|
||||
// Phone: user.Phone,
|
||||
// Email: user.UserEmail,
|
||||
// GoogleSecret: authSwitch.GoogleSecret,
|
||||
// SmsCaptcha: rpc.SmsCaptcha,
|
||||
// EmailCaptcha: rpc.EmailCaptcha,
|
||||
// GoogleCaptcha: rpc.GoogleCaptcha,
|
||||
// BusinessType: businesstype.ResetPass,
|
||||
// }
|
||||
//
|
||||
// if code := AuthenticatorVerify(orm, validator); code != statuscode.OK {
|
||||
// return "", code
|
||||
// }
|
||||
//
|
||||
// // 校验验证码通过,生成下一步操作的凭证
|
||||
// cre := sysmodel.Credential{
|
||||
// BusinessType: int(businesstype.ResetPass),
|
||||
// UserID: user.Id,
|
||||
// Phone: user.Phone,
|
||||
// Email: user.UserEmail,
|
||||
// Time: time.Now().Unix(),
|
||||
// Rand: rand.NewSource(time.Now().UnixNano()).Int63(),
|
||||
// }
|
||||
// creJ, _ := sonic.Marshal(cre)
|
||||
// credentials := aeshelper.Encrypt(string(creJ), codeVerifySuccess)
|
||||
//
|
||||
// return credentials, statuscode.OK
|
||||
//}
|
||||
//
|
||||
//// ResetPwd 3 重置密码
|
||||
//func ResetPwd(orm *gorm.DB, user models.AdUser, resetPwd sysmodel.ResetPwdReq) int {
|
||||
// // 校验凭证
|
||||
// cre := sysmodel.Credential{
|
||||
// BusinessType: int(businesstype.ResetPass),
|
||||
// UserID: user.Id,
|
||||
// Phone: user.Phone,
|
||||
// Email: user.UserEmail,
|
||||
// Time: time.Now().Unix(),
|
||||
// }
|
||||
// if !CheckCredentials(cre, resetPwd.Credentials) {
|
||||
// log.Error("business credentials error")
|
||||
// return statuscode.BusinessCredentialsError
|
||||
// }
|
||||
//
|
||||
// // 更新密码
|
||||
// if err := aduserdb.UpdateUserPwd(orm, resetPwd.UserID, resetPwd.Password); err != nil {
|
||||
// return statuscode.ServerError
|
||||
// }
|
||||
//
|
||||
// return statuscode.OK
|
||||
//}
|
||||
//
|
||||
//// ChangePwdBefore 修改密码前校验
|
||||
//func ChangePwdBefore(orm *gorm.DB, params sysmodel.UserChangePwdReq) (user models.AdUser, code int) {
|
||||
//
|
||||
// user, err := aduserdb.GetUserById(orm, params.UserId) //"id", params.UserId)
|
||||
//
|
||||
// if err != nil {
|
||||
// return user, statuscode.ServerError
|
||||
// }
|
||||
// if user.UserPassword != params.OldPassword {
|
||||
// return user, statuscode.OriginalPasswordError
|
||||
// }
|
||||
//
|
||||
// return user, statuscode.OK
|
||||
//}
|
||||
//
|
||||
//// ChangePwd 修改密码
|
||||
//func ChangePwd(orm *gorm.DB, params sysmodel.UserChangePwdReq, user models.AdUser) int {
|
||||
// // 获取用户验证器开关状态
|
||||
// authSwitch, err := GetUserAuthSwitch(orm, user.Id)
|
||||
// if err != nil {
|
||||
// return statuscode.ServerError
|
||||
// }
|
||||
//
|
||||
// // 验证器验证
|
||||
// auth := sysmodel.Authenticator{
|
||||
// UserID: params.UserId,
|
||||
// PhoneAuth: authSwitch.PhoneAuth,
|
||||
// EmailAuth: authSwitch.EmailAuth,
|
||||
// GoogleAuth: authSwitch.GoogleAuth,
|
||||
// Phone: user.Phone,
|
||||
// Email: user.UserEmail,
|
||||
// GoogleSecret: authSwitch.GoogleSecret,
|
||||
// SmsCaptcha: params.SmsCaptcha,
|
||||
// EmailCaptcha: params.EmailCaptcha,
|
||||
// GoogleCaptcha: params.GoogleCaptcha,
|
||||
// BusinessType: businesstype.ChangePassword,
|
||||
// }
|
||||
// if code := AuthenticatorVerify(orm, auth); code != statuscode.OK {
|
||||
// return code
|
||||
// }
|
||||
//
|
||||
// // 更新密码
|
||||
// if err = aduserdb.UpdateUserPwd(orm, params.UserId, params.NewPassword); err != nil {
|
||||
// return statuscode.ServerError
|
||||
// }
|
||||
//
|
||||
// return statuscode.OK
|
||||
//}
|
||||
//
|
||||
//// GetUserRealName 获取用户真实姓名
|
||||
//func GetUserRealName(orm *gorm.DB, uid int) string {
|
||||
// buyerIdent, err := aduserdb.GetIdentification(orm, uid)
|
||||
// if err != nil {
|
||||
// return ""
|
||||
// }
|
||||
// realName := buyerIdent.Name
|
||||
//
|
||||
// if buyerIdent.CountryId == 40 || buyerIdent.CountryId == 73 ||
|
||||
// buyerIdent.CountryId == 115 || buyerIdent.CountryId == 179 {
|
||||
// realName = buyerIdent.Name // 中国大陆,港澳台
|
||||
// } else {
|
||||
// // 名字-中间名-姓
|
||||
// realName = buyerIdent.Name + " " + buyerIdent.MiddleName + " " + buyerIdent.Surname
|
||||
// }
|
||||
//
|
||||
// return realName
|
||||
//}
|
||||
402
common/service/sysservice/authservice/authenticator.go
Normal file
402
common/service/sysservice/authservice/authenticator.go
Normal file
@ -0,0 +1,402 @@
|
||||
package authservice
|
||||
|
||||
//
|
||||
//import (
|
||||
// "go-admin/app/admin/models"
|
||||
// "go-admin/app/admin/models/sysmodel"
|
||||
// "go-admin/app/admin/service/aduserdb"
|
||||
// "go-admin/app/admin/service/otcdb/orderdb"
|
||||
// "go-admin/common/const/enum/businesstype"
|
||||
// statuscode "go-admin/common/status_code"
|
||||
// "go-admin/pkg/googleauthhelper"
|
||||
// "go-admin/pkg/utility"
|
||||
//
|
||||
// log "github.com/go-admin-team/go-admin-core/logger"
|
||||
// "gorm.io/gorm"
|
||||
//
|
||||
// "go.uber.org/zap"
|
||||
//)
|
||||
//
|
||||
//// GetUserAuthSwitch 获取用户验证器开关状态
|
||||
//func GetUserAuthSwitch(orm *gorm.DB, userID int) (auth sysmodel.UserAuthSwitchStatus, err error) {
|
||||
// // 获取用户验证器开关
|
||||
// auth, err = aduserdb.GetUserAuthSwitch(orm, userID)
|
||||
// if err != nil {
|
||||
// return
|
||||
// }
|
||||
//
|
||||
// if auth.PhoneAuth != 1 {
|
||||
// auth.PhoneAuth = 0
|
||||
// }
|
||||
// if auth.EmailAuth != 1 {
|
||||
// auth.EmailAuth = 0
|
||||
// }
|
||||
// if auth.GoogleAuth != 1 {
|
||||
// auth.GoogleAuth = 0
|
||||
// }
|
||||
//
|
||||
// return
|
||||
//}
|
||||
//
|
||||
//// AuthenticatorVerify 已开通验证器校验
|
||||
//func AuthenticatorVerify(orm *gorm.DB, authenticator sysmodel.Authenticator) int {
|
||||
// // 是否完全验证
|
||||
// if authenticator.PhoneAuth == 1 && len(authenticator.SmsCaptcha) == 0 ||
|
||||
// authenticator.EmailAuth == 1 && len(authenticator.EmailCaptcha) == 0 ||
|
||||
// authenticator.GoogleAuth == 1 && len(authenticator.GoogleCaptcha) == 0 {
|
||||
//
|
||||
// return statuscode.PleasePerformCompleteSecurityVerification
|
||||
// }
|
||||
// var phoneCheck sysmodel.CheckCaptcha
|
||||
// var emailCheck sysmodel.CheckCaptcha
|
||||
// // 校验验证码
|
||||
// if authenticator.PhoneAuth == 1 {
|
||||
// phoneCheck = sysmodel.CheckCaptcha{
|
||||
// BusinessType: int(authenticator.BusinessType),
|
||||
// Receive: authenticator.Phone,
|
||||
// Captcha: authenticator.SmsCaptcha,
|
||||
// }
|
||||
// }
|
||||
// if authenticator.EmailAuth == 1 {
|
||||
// emailCheck = sysmodel.CheckCaptcha{
|
||||
// BusinessType: int(authenticator.BusinessType),
|
||||
// Receive: authenticator.Email,
|
||||
// Captcha: authenticator.EmailCaptcha,
|
||||
// }
|
||||
// }
|
||||
// var googleSecret string
|
||||
// var googleCaptcha string
|
||||
// if authenticator.GoogleAuth == 1 {
|
||||
// googleSecret = authenticator.GoogleSecret
|
||||
// googleCaptcha = authenticator.GoogleCaptcha
|
||||
// }
|
||||
// // 检验验证码
|
||||
// code := CheckCaptchaNew(orm, phoneCheck, emailCheck, googleSecret, googleCaptcha)
|
||||
// return code
|
||||
//}
|
||||
//
|
||||
//// AuthSwitchBefore 身份验证开关前校验(新)
|
||||
//func AuthSwitchBefore(orm *gorm.DB, auth sysmodel.AuthenticatorSwitch) int {
|
||||
// // 开启手机、更改手机、开启邮箱、更改邮箱 判断是否被占用
|
||||
// var user models.AdUser
|
||||
// var err error
|
||||
// if auth.BusinessType == businesstype.OpenPhoneAuth || auth.BusinessType == businesstype.ChangePhoneAuth {
|
||||
// user, err = aduserdb.GetUserByPhone(orm, auth.NewPhoneArea, auth.NewPhone)
|
||||
// if err != nil {
|
||||
// return statuscode.ServerError
|
||||
// }
|
||||
// if user.Id != 0 && user.Id != auth.UserID {
|
||||
// return statuscode.ThePhoneHasBeenBound
|
||||
// }
|
||||
// } else if auth.BusinessType == businesstype.OpenEmailAuth || auth.BusinessType == businesstype.ChangeEmailAuth {
|
||||
// user, err = aduserdb.GetUserByEmail(orm, auth.NewEmail) //GetUser("useremail", auth.NewEmail)
|
||||
// if err != nil {
|
||||
// return statuscode.ServerError
|
||||
// }
|
||||
// if user.Id != 0 && user.Id != auth.UserID {
|
||||
// return statuscode.TheEmailHasBeenBound
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// // 获取用户验证器开关状态
|
||||
// authSwitch, err := GetUserAuthSwitch(orm, auth.UserID)
|
||||
// if err != nil {
|
||||
// return statuscode.ServerError
|
||||
// }
|
||||
//
|
||||
// // 关闭验证器 需保证至少两个开启
|
||||
// if auth.BusinessType == businesstype.ClosePhoneAuth ||
|
||||
// auth.BusinessType == businesstype.CloseEmailAuth ||
|
||||
// auth.BusinessType == businesstype.CloseGoogleAuth {
|
||||
//
|
||||
// if (authSwitch.PhoneAuth + authSwitch.EmailAuth + authSwitch.GoogleAuth) < 3 {
|
||||
// return statuscode.AllAuthMustOpen
|
||||
// }
|
||||
//
|
||||
// // OTC 订单状态为:1-待付款、3-代放币、7-申诉中时,不允许解绑手机
|
||||
// if auth.BusinessType == businesstype.ClosePhoneAuth {
|
||||
// // hc todo 注释
|
||||
// // 广告
|
||||
// // sum, err := advertisedb.GetUserAdvertiseSum(auth.UserID)
|
||||
// // if err != nil {
|
||||
// // return statuscode.ServerError
|
||||
// // }
|
||||
// // if sum > 0 {
|
||||
// // return statuscode.OTCAdvertiseAreInProgress
|
||||
// // }
|
||||
// // 订单
|
||||
// num, err := orderdb.GetUnfilledOrderCount(orm, auth.UserID)
|
||||
// if err != nil {
|
||||
// return statuscode.ServerError
|
||||
// }
|
||||
// if num > 0 {
|
||||
// return statuscode.OTCOrdersAreInProgress
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// if user.Id == 0 {
|
||||
// user, err = aduserdb.GetUserById(orm, auth.UserID) //"id", auth.UserID)
|
||||
// if err != nil {
|
||||
// return statuscode.ServerError
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// // ==================== 1 已开通验证器校验 ==================== //
|
||||
// validator := sysmodel.Authenticator{
|
||||
// UserID: auth.UserID,
|
||||
// PhoneAuth: authSwitch.PhoneAuth,
|
||||
// EmailAuth: authSwitch.EmailAuth,
|
||||
// GoogleAuth: authSwitch.GoogleAuth,
|
||||
// Phone: user.Phone,
|
||||
// Email: user.UserEmail,
|
||||
// GoogleSecret: authSwitch.GoogleSecret,
|
||||
// SmsCaptcha: auth.SmsCaptcha,
|
||||
// EmailCaptcha: auth.EmailCaptcha,
|
||||
// GoogleCaptcha: auth.GoogleCaptcha,
|
||||
// BusinessType: auth.BusinessType,
|
||||
// }
|
||||
//
|
||||
// // 是否完全验证
|
||||
// if validator.PhoneAuth == 1 && len(validator.SmsCaptcha) == 0 ||
|
||||
// validator.EmailAuth == 1 && len(validator.EmailCaptcha) == 0 ||
|
||||
// validator.GoogleAuth == 1 && len(validator.GoogleCaptcha) == 0 {
|
||||
//
|
||||
// return statuscode.PleasePerformCompleteSecurityVerification
|
||||
// }
|
||||
// var phoneCode models.AdVerifyCode
|
||||
// if len(validator.SmsCaptcha) > 0 && !CheckOpenVerifyCode(validator.SmsCaptcha) {
|
||||
// // 校验手机号码发送的验证码
|
||||
// phoneCheck := sysmodel.CheckCaptcha{
|
||||
// BusinessType: int(businesstype.WithdrawAuth),
|
||||
// Receive: validator.Phone,
|
||||
// Captcha: validator.SmsCaptcha,
|
||||
// }
|
||||
// phoneCode = aduserdb.GetVerifyCode(orm, phoneCheck)
|
||||
// if phoneCode.Id == 0 {
|
||||
// return statuscode.PhoneCaptchaInvalid
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// var emailCode models.AdVerifyCode
|
||||
// if len(validator.EmailCaptcha) > 0 && !CheckOpenVerifyCode(validator.EmailCaptcha) {
|
||||
// // 校验邮箱号码发送的验证码
|
||||
// emailCheck := sysmodel.CheckCaptcha{
|
||||
// BusinessType: int(businesstype.WithdrawAuth),
|
||||
// Receive: validator.Email,
|
||||
// Captcha: validator.EmailCaptcha,
|
||||
// }
|
||||
// emailCode = aduserdb.GetVerifyCode(orm, emailCheck)
|
||||
// if emailCode.Id == 0 {
|
||||
// return statuscode.EmailCaptchaInvalid
|
||||
// }
|
||||
// }
|
||||
// if len(validator.GoogleCaptcha) > 0 {
|
||||
// // 校验谷歌的验证码
|
||||
// auth2 := googleauthhelper.VerifyCode(validator.GoogleSecret, utility.StringAsInt32(validator.GoogleCaptcha))
|
||||
// if !auth2 {
|
||||
// return statuscode.GoogleCaptchaInvalid
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// // ==================== 2 新绑定的验证器校验 ==================== //
|
||||
// var phoneNewCode models.AdVerifyCode
|
||||
// // 开启手机|更改手机验证 都需要校验新手机
|
||||
// if auth.BusinessType == businesstype.OpenPhoneAuth || auth.BusinessType == businesstype.ChangePhoneAuth {
|
||||
// if !CheckOpenVerifyCode(auth.NewPhoneCaptcha) {
|
||||
// cc := sysmodel.CheckCaptcha{
|
||||
// BusinessType: int(auth.BusinessType),
|
||||
// Receive: auth.NewPhone,
|
||||
// Captcha: auth.NewPhoneCaptcha,
|
||||
// }
|
||||
// phoneNewCode = aduserdb.GetVerifyCode(orm, cc)
|
||||
// if phoneNewCode.Id == 0 {
|
||||
// return statuscode.NewPhoneCaptchaInvalid
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// var emailNewCode models.AdVerifyCode
|
||||
// // 开启邮箱|更改邮箱验证 都需要校验新邮箱
|
||||
// if auth.BusinessType == businesstype.OpenEmailAuth || auth.BusinessType == businesstype.ChangeEmailAuth {
|
||||
// if !CheckOpenVerifyCode(auth.NewEmailCaptcha) {
|
||||
// cc := sysmodel.CheckCaptcha{
|
||||
// BusinessType: int(auth.BusinessType),
|
||||
// Receive: auth.NewEmail,
|
||||
// Captcha: auth.NewEmailCaptcha,
|
||||
// }
|
||||
// emailNewCode = aduserdb.GetVerifyCode(orm, cc)
|
||||
// if emailNewCode.Id == 0 {
|
||||
// return statuscode.NewEmailCaptchaInvalid
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// // 开启谷歌验证器 需要验证谷歌
|
||||
// if auth.BusinessType == businesstype.OpenGoogleAuth {
|
||||
// newSecret, _ := aduserdb.GetNewGoogleSecret(orm, auth.UserID)
|
||||
// if ok := googleauthhelper.VerifyCode(newSecret, utility.StringAsInt32(auth.NewGoogleCaptcha)); !ok {
|
||||
// // tx.Rollback()
|
||||
// log.Error("google验证码校验失败")
|
||||
// return statuscode.GoogleCaptchaInvalid
|
||||
// }
|
||||
// }
|
||||
// if phoneCode.Id == 0 && phoneNewCode.Id == 0 && emailCode.Id == 0 && emailNewCode.Id == 0 {
|
||||
// log.Error("AuthSwitchBefore", zap.String("没验证旧手机、新手机、旧邮箱、新邮箱,估计只验证谷歌验证器",
|
||||
// "phoneCode.Id ==0 && phoneNewCode.Id ==0 && emailCode.Id ==0&& emailNewCode.Id ==0"))
|
||||
// return statuscode.OK
|
||||
// }
|
||||
//
|
||||
// var transCode int
|
||||
// err = orm.Transaction(func(tx *gorm.DB) error {
|
||||
// // ==================== 1 已开通验证器校验,修改表数据为已验证 ==================== //
|
||||
// if phoneCode.Id > 0 { // 旧手机验证码修改
|
||||
// err := aduserdb.UpdateVerifyFlag(tx, phoneCode.Id)
|
||||
// if err != nil {
|
||||
// log.Error("AuthSwitchBefore phoneCode", zap.Error(err))
|
||||
// // _ = tx.Rollback()
|
||||
// transCode = statuscode.PhoneCaptchaInvalid
|
||||
// return err
|
||||
// }
|
||||
// }
|
||||
// if emailCode.Id > 0 { // 旧邮箱验证码修改
|
||||
// err = aduserdb.UpdateVerifyFlag(tx, emailCode.Id)
|
||||
// if err != nil {
|
||||
// log.Error("AuthSwitchBefore emailCode", zap.Error(err))
|
||||
// // _ = tx.Rollback()
|
||||
// transCode = statuscode.EmailCaptchaInvalid
|
||||
//
|
||||
// return err
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// // ==================== 2 新绑定的验证器校验,修改表数据为已验证 ==================== //
|
||||
// if phoneNewCode.Id > 0 { // 新手机验证码修改
|
||||
// err = aduserdb.UpdateVerifyFlag(tx, phoneNewCode.Id)
|
||||
// if err != nil {
|
||||
// log.Error("AuthSwitchBefore phoneNewCode", zap.Error(err))
|
||||
//
|
||||
// transCode = statuscode.PhoneCaptchaInvalid
|
||||
//
|
||||
// return err
|
||||
// }
|
||||
// }
|
||||
// if emailNewCode.Id > 0 { // 新邮箱验证码修改
|
||||
// err = aduserdb.UpdateVerifyFlag(tx, emailNewCode.Id)
|
||||
// if err != nil {
|
||||
// log.Error("AuthSwitchBefore emailNewCode", zap.Error(err))
|
||||
//
|
||||
// transCode = statuscode.EmailCaptchaInvalid
|
||||
//
|
||||
// return err
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// return nil
|
||||
// })
|
||||
// // 开启事务
|
||||
// // tx, err := dbhelper.MasterPgdb.Beginx()
|
||||
// // if err != nil {
|
||||
// // return statuscode.ServerError
|
||||
// // }
|
||||
//
|
||||
// // // ==================== 1 已开通验证器校验,修改表数据为已验证 ==================== //
|
||||
// // if phoneCode.Id > 0 { // 旧手机验证码修改
|
||||
// // err = aduserdb.UpdateVerifyFlag(phoneCode.Id, tx)
|
||||
// // if err != nil {
|
||||
// // log.Error("AuthSwitchBefore phoneCode", zap.Error(err))
|
||||
// // _ = tx.Rollback()
|
||||
// // return statuscode.PhoneCaptchaInvalid
|
||||
// // }
|
||||
// // }
|
||||
// // if emailCode.Id > 0 { // 旧邮箱验证码修改
|
||||
// // err = aduserdb.UpdateVerifyFlag(emailCode.Id, tx)
|
||||
// // if err != nil {
|
||||
// // log.Error("AuthSwitchBefore emailCode", zap.Error(err))
|
||||
// // _ = tx.Rollback()
|
||||
// // return statuscode.EmailCaptchaInvalid
|
||||
// // }
|
||||
// // }
|
||||
//
|
||||
// // // ==================== 2 新绑定的验证器校验,修改表数据为已验证 ==================== //
|
||||
// // if phoneNewCode.Id > 0 { // 新手机验证码修改
|
||||
// // err = aduserdb.UpdateVerifyFlag(phoneNewCode.Id, tx)
|
||||
// // if err != nil {
|
||||
// // log.Error("AuthSwitchBefore phoneNewCode", zap.Error(err))
|
||||
// // _ = tx.Rollback()
|
||||
// // return statuscode.PhoneCaptchaInvalid
|
||||
// // }
|
||||
// // }
|
||||
// // if emailNewCode.Id > 0 { // 新邮箱验证码修改
|
||||
// // err = aduserdb.UpdateVerifyFlag(emailNewCode.Id, tx)
|
||||
// // if err != nil {
|
||||
// // log.Error("AuthSwitchBefore emailNewCode", zap.Error(err))
|
||||
// // _ = tx.Rollback()
|
||||
// // return statuscode.EmailCaptchaInvalid
|
||||
// // }
|
||||
// // }
|
||||
// // // 提交事务
|
||||
// // if err = tx.Commit(); err != nil {
|
||||
// // return statuscode.ServerError
|
||||
// // }
|
||||
//
|
||||
// if err != nil {
|
||||
// return transCode
|
||||
// }
|
||||
// return statuscode.OK
|
||||
//}
|
||||
//
|
||||
//// AuthSwitchNew 身份验证开关(新)
|
||||
//func AuthSwitchNew(orm *gorm.DB, auth sysmodel.AuthenticatorSwitch) int {
|
||||
// // 验证器-开关
|
||||
// switch auth.BusinessType {
|
||||
// case businesstype.OpenPhoneAuth:
|
||||
// if err := aduserdb.BindPhoneAuth(orm, auth.UserID, auth.NewPhoneArea, auth.NewPhone); err != nil {
|
||||
// return statuscode.ServerError
|
||||
// }
|
||||
// case businesstype.ChangePhoneAuth:
|
||||
// if err := aduserdb.ChangePhoneAuth(orm, auth.UserID, auth.NewPhoneArea, auth.NewPhone); err != nil {
|
||||
// return statuscode.ServerError
|
||||
// }
|
||||
// // hc todo 注释掉 先不急
|
||||
// // 更新商家信息
|
||||
// // merchant := merchantdb.GetMerchantInfoForUserId(orm, auth.UserID)
|
||||
// // if merchant.Id > 0 {
|
||||
// // _ = merchantdb.UpdateMerchantMobile(auth.UserID, auth.NewPhone)
|
||||
// // }
|
||||
// case businesstype.ClosePhoneAuth:
|
||||
// if err := aduserdb.ClosePhoneAuth(orm, auth.UserID); err != nil {
|
||||
// return statuscode.ServerError
|
||||
// }
|
||||
//
|
||||
// case businesstype.OpenEmailAuth:
|
||||
// if err := aduserdb.BindEmailAuth(orm, auth.UserID, auth.NewEmail); err != nil {
|
||||
// return statuscode.ServerError
|
||||
// }
|
||||
// case businesstype.ChangeEmailAuth:
|
||||
// if err := aduserdb.ChangeEmailAuth(orm, auth.UserID, auth.NewEmail); err != nil {
|
||||
// return statuscode.ServerError
|
||||
// }
|
||||
// case businesstype.CloseEmailAuth:
|
||||
// if err := aduserdb.CloseEmailAuth(orm, auth.UserID); err != nil {
|
||||
// return statuscode.ServerError
|
||||
// }
|
||||
//
|
||||
// case businesstype.OpenGoogleAuth:
|
||||
// if err := aduserdb.OpenGoogleAuth(orm, auth.UserID); err != nil {
|
||||
// return statuscode.ServerError
|
||||
// }
|
||||
// case businesstype.ChangeGoogleAuth:
|
||||
// if err := aduserdb.CloseGoogleAuth(orm, auth.UserID); err != nil {
|
||||
// return statuscode.ServerError
|
||||
// }
|
||||
// case businesstype.CloseGoogleAuth:
|
||||
// if err := aduserdb.CloseGoogleAuth(orm, auth.UserID); err != nil {
|
||||
// return statuscode.ServerError
|
||||
// }
|
||||
//
|
||||
// default:
|
||||
// return statuscode.ParameterInvalid
|
||||
// }
|
||||
//
|
||||
// return statuscode.OK
|
||||
//}
|
||||
542
common/service/sysservice/authservice/captcha.go
Normal file
542
common/service/sysservice/authservice/captcha.go
Normal file
@ -0,0 +1,542 @@
|
||||
package authservice
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"github.com/bytedance/sonic"
|
||||
log "github.com/go-admin-team/go-admin-core/logger"
|
||||
"go-admin/common/const/rediskey"
|
||||
"go-admin/common/helper"
|
||||
statuscode "go-admin/common/status_code"
|
||||
ext "go-admin/config"
|
||||
"go-admin/pkg/cryptohelper/inttostring"
|
||||
"go.uber.org/zap"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
//
|
||||
//// SendCaptchaBefore 发送验证码前之前检查
|
||||
//func SendCaptchaBefore(orm *gorm.DB, auth sysmodel.SendCaptchaReq) int {
|
||||
// var (
|
||||
// user models.AdUser
|
||||
// err error
|
||||
// )
|
||||
//
|
||||
// // 除 注册、开启手机|邮箱验证、更改手机|邮箱验证 外,
|
||||
// // 其余业务发送前都需验证账号是否存在
|
||||
// if !(auth.BusinessType == int(businesstype.Register) ||
|
||||
// auth.BusinessType == int(businesstype.OpenPhoneAuth) ||
|
||||
// auth.BusinessType == int(businesstype.OpenEmailAuth) ||
|
||||
// auth.IsNew == 1 && auth.BusinessType == int(businesstype.ChangePhoneAuth) ||
|
||||
// auth.IsNew == 1 && auth.BusinessType == int(businesstype.ChangeEmailAuth)) {
|
||||
//
|
||||
// if auth.SendType == sysmodel.TSmsCode {
|
||||
// // 手机
|
||||
// user, err = aduserdb.GetUserByPhone(orm, auth.PhoneAreaCode, auth.Phone)
|
||||
// if err != nil {
|
||||
// return statuscode.ServerError
|
||||
// }
|
||||
// } else if auth.SendType == sysmodel.TEmailCode {
|
||||
// // 邮箱
|
||||
// user, err = aduserdb.GetUserByEmail(orm, auth.Email) //GetUser("useremail", auth.Email)
|
||||
// if err != nil {
|
||||
// return statuscode.ServerError
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// // 账号不存在
|
||||
// if user.Id == 0 {
|
||||
// return statuscode.TheAccountIsNotRegistered
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// // 除:1 注册、2 登录、3 找回密码外,其余业务都需要登录(直接通过 uid 获取登录用户)
|
||||
// if auth.BusinessType > 3 {
|
||||
// user, err = aduserdb.GetUserById(orm, auth.Uid) //"id", auth.Uid)
|
||||
// if err != nil {
|
||||
// return statuscode.ServerError
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// // 开启手机、开启邮箱 判断号码是否被占用(自己的号码判定为不占用)
|
||||
// if auth.BusinessType == int(businesstype.OpenPhoneAuth) || auth.BusinessType == int(businesstype.OpenEmailAuth) {
|
||||
// if auth.SendType == sysmodel.TSmsCode {
|
||||
// // 手机
|
||||
// user, err = aduserdb.GetUserByPhone(orm, auth.PhoneAreaCode, auth.Phone)
|
||||
// if err != nil {
|
||||
// return statuscode.ServerError
|
||||
// }
|
||||
//
|
||||
// if user.Id != 0 && user.Id != auth.Uid {
|
||||
// return statuscode.ThePhoneHasBeenBound
|
||||
// }
|
||||
// } else if auth.SendType == sysmodel.TEmailCode {
|
||||
// // 邮箱
|
||||
// user, err = aduserdb.GetUserByEmail(orm, auth.Email) //GetUser("useremail", auth.Email)
|
||||
// if err != nil {
|
||||
// return statuscode.ServerError
|
||||
// }
|
||||
//
|
||||
// if user.Id != 0 && user.Id != auth.Uid {
|
||||
// return statuscode.TheEmailHasBeenBound
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// // 更改手机、更改邮箱 仅判断新号码是否被占用(自己的号码判定为占用)
|
||||
// if auth.IsNew == 1 &&
|
||||
// (auth.BusinessType == int(businesstype.ChangePhoneAuth) || auth.BusinessType == int(businesstype.ChangeEmailAuth)) {
|
||||
//
|
||||
// if auth.SendType == sysmodel.TSmsCode {
|
||||
// // 手机
|
||||
// user, err = aduserdb.GetUserByPhone(orm, auth.PhoneAreaCode, auth.Phone)
|
||||
// if err != nil {
|
||||
// return statuscode.ServerError
|
||||
// }
|
||||
//
|
||||
// if user.Id != 0 {
|
||||
// return statuscode.ThePhoneHasBeenBound
|
||||
// }
|
||||
// } else if auth.SendType == sysmodel.TEmailCode {
|
||||
// // 邮箱
|
||||
// user, err = aduserdb.GetUserByEmail(orm, auth.Email) //GetUser("useremail", auth.Email)
|
||||
// if err != nil {
|
||||
// return statuscode.ServerError
|
||||
// }
|
||||
//
|
||||
// if user.Id != 0 {
|
||||
// return statuscode.TheEmailHasBeenBound
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// // 发送次数校验
|
||||
// var sign interface{} = auth.Uid
|
||||
// if sign == 0 {
|
||||
// sign = auth.IP
|
||||
// }
|
||||
// key := fmt.Sprintf(rediskey.UserCaptchaSendFre, sign, auth.BusinessType)
|
||||
//
|
||||
// if countStr, err2 := helper.DefaultRedis.GetString(key); err2 == nil {
|
||||
// count, _ := strconv.Atoi(countStr)
|
||||
//
|
||||
// if count >= 20 {
|
||||
// return statuscode.CaptchaSendFrequencyExceedLimit
|
||||
// }
|
||||
// }
|
||||
// /*if auth.BusinessType == int(enum.Register) {
|
||||
// if count > 0 {
|
||||
// return enum.CaptchaSendFrequencyExceedLimit
|
||||
// }
|
||||
// } else {
|
||||
// if count >= 20 {
|
||||
// return enum.CaptchaSendFrequencyExceedLimit
|
||||
// }
|
||||
// }*/
|
||||
//
|
||||
// return statuscode.OK
|
||||
//}
|
||||
//
|
||||
//// IsRepeatSend 是否重复发送验证码
|
||||
//func IsRepeatSend(orm *gorm.DB, receive string, businessType int) (bool, int) {
|
||||
// verifyCode, err := aduserdb.IsRepeatSend(orm, receive, businessType)
|
||||
// if err != nil {
|
||||
// return false, 0
|
||||
// }
|
||||
//
|
||||
// if verifyCode.Id != 0 {
|
||||
// // 给 send 加时区,保持与当前时区一致
|
||||
// send := verifyCode.SendTime
|
||||
// send = time.Date(send.Year(), send.Month(), send.Day(), send.Hour(), send.Minute(), send.Second(), send.Nanosecond(), time.Local)
|
||||
//
|
||||
// // wait = send+60-now
|
||||
// wait := send.Add(time.Minute).Sub(time.Now()).Seconds()
|
||||
// return true, int(wait)
|
||||
// }
|
||||
//
|
||||
// return false, 0
|
||||
//}
|
||||
//
|
||||
//// 生成验证码
|
||||
//func genVerifyCode() string {
|
||||
// return fmt.Sprintf("%06v", rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(1000000))
|
||||
//}
|
||||
//
|
||||
////// 阿里云 - 发送手机验证码
|
||||
////func SendALYSms(areaPhoneCode, phoneNumber string, businessType int) error {
|
||||
////
|
||||
//// var smsCode = genVerifyCode()
|
||||
////
|
||||
//// resp, err := smshelper.SendALYSmsCode(areaPhoneCode, phoneNumber, smsCode)
|
||||
//// if err != nil {
|
||||
//// return err
|
||||
//// }
|
||||
////
|
||||
//// if *resp.Code != "OK" || *resp.Message != "OK" {
|
||||
//// return errors.New(*resp.Message)
|
||||
//// }
|
||||
////
|
||||
//// if err := RecordAuthCode(smsCode, phoneNumber, businessType); err != nil {
|
||||
//// log.Error("record sms auth code", zap.Error(err))
|
||||
//// return errors.New("this sms verification code is invalid")
|
||||
//// }
|
||||
////
|
||||
//// return nil
|
||||
////}
|
||||
//
|
||||
//// SendXDYSms 信达云 - 发送手机验证码
|
||||
//func SendXDYSms(orm *gorm.DB, areaPhoneCode, phoneNumber string, businessType int) error {
|
||||
// // SMS 模板
|
||||
// msgBody := ""
|
||||
// business := ""
|
||||
// if businessType <= 102 {
|
||||
// // <100 用通用模板
|
||||
// msgBody = smstemplate.SmsTemplate_1_CN
|
||||
// business = businesstype.BusinessTypeMapCN[businesstype.BusinessType(businessType)]
|
||||
// if areaPhoneCode != "86" {
|
||||
// msgBody = smstemplate.SmsTemplate_1_EN
|
||||
// business = businesstype.BusinessTypeMapEN[businesstype.BusinessType(businessType)]
|
||||
//
|
||||
// }
|
||||
// } else {
|
||||
// //暂时只写中文 通用验证码
|
||||
// msgBody = smstemplate.SmsTemplate_1_CN
|
||||
// business = businesstype.BusinessTypeMapCN[businesstype.BusinessType(businessType)]
|
||||
// }
|
||||
//
|
||||
// // 内容替换
|
||||
// var smsCode = genVerifyCode()
|
||||
// msgBody = strings.Replace(msgBody, "${business}", business, 1)
|
||||
// msgBody = strings.Replace(msgBody, "${code}", smsCode, 1)
|
||||
//
|
||||
// // 发送验证码
|
||||
// _, err := smshelper.SendDXYSmsCode(areaPhoneCode, phoneNumber, msgBody)
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
//
|
||||
// // 记录验证码
|
||||
// if err := RecordAuthCode(orm, smsCode, phoneNumber, businessType); err != nil {
|
||||
// log.Error("record sms auth code", zap.Error(err))
|
||||
// return errors.New("this sms verification code is invalid")
|
||||
// }
|
||||
//
|
||||
// return nil
|
||||
//}
|
||||
//
|
||||
//// XindaCloud 回执报告
|
||||
////func XindaCloudReceipt(ctx *fiber.Ctx) error {
|
||||
//// var req interface{}
|
||||
//// if err := ctx.BodyParser(&req); err != nil {
|
||||
//// log.Error("BodyParser", zap.Error(err))
|
||||
//// }
|
||||
////
|
||||
//// _ = redishelper.HMSet("XindaCloudReceipt", req)
|
||||
////
|
||||
//// return nil
|
||||
////}
|
||||
//
|
||||
////// SendUserEmail 发送邮箱验证码
|
||||
////func SendUserEmail(sendTo string, businessType int) error {
|
||||
//// // 生成随机验证码
|
||||
//// emailCode := genVerifyCode()
|
||||
////
|
||||
//// send := config.EmailSend{
|
||||
//// EmailConfig: config.AppGlobalConfig.EmailConfig,
|
||||
//// Subject: "邮箱验证码",
|
||||
//// Content: "[HS] 您的邮箱验证码为: " + emailCode,
|
||||
//// To: sendTo,
|
||||
//// }
|
||||
////
|
||||
//// if _, ok := emailhelper.SendEmail(send); ok {
|
||||
//// if err := RecordAuthCode(emailCode, sendTo, businessType); err != nil {
|
||||
//// log.Error("record email auth code", zap.Error(err))
|
||||
//// return errors.New("this email verification code is invalid")
|
||||
//// }
|
||||
////
|
||||
//// return nil
|
||||
//// }
|
||||
////
|
||||
//// return errors.New("email send failed")
|
||||
////}
|
||||
//
|
||||
//func MailJetSend(orm *gorm.DB, receive string, businessType int) error {
|
||||
// // 生成随机验证码
|
||||
// code := genVerifyCode()
|
||||
//
|
||||
// if err := emailhelper.MailJetSend(receive, code); err != nil {
|
||||
// return err
|
||||
// }
|
||||
//
|
||||
// if err := RecordAuthCode(orm, code, receive, businessType); err != nil {
|
||||
// log.Error("record email auth code", zap.Error(err))
|
||||
// return errors.New("record email auth code failed")
|
||||
// }
|
||||
//
|
||||
// return nil
|
||||
//}
|
||||
//
|
||||
//// RecordAuthCode 记录验证码
|
||||
//func RecordAuthCode(orm *gorm.DB, authCode, receive string, businessType int) error {
|
||||
// var (
|
||||
// sendTime = time.Now()
|
||||
// expireTime = sendTime.Add(sysmodel.CodeValidTime)
|
||||
// )
|
||||
//
|
||||
// var authCodeInfo = &models.AdVerifyCode{
|
||||
// Phone: receive,
|
||||
// Code: authCode,
|
||||
// SendTime: sendTime,
|
||||
// ValidTimeLen: int(sysmodel.CodeValidTime.Seconds()),
|
||||
// VerifyTime: expireTime,
|
||||
// VerifyFlag: 0,
|
||||
// BusinessType: businessType,
|
||||
// }
|
||||
//
|
||||
// return orm.Model(authCodeInfo).Create(authCodeInfo).Error
|
||||
// // return dbhelper.MasterPgdb.Insert("ad_verifycode", authCodeInfo)
|
||||
//}
|
||||
//
|
||||
//// // CheckCaptcha 校验验证码
|
||||
//// func CheckCaptcha(cc sysmodel.CheckCaptcha, tx *sqlx.Tx) error {
|
||||
//// // TODO 免检测验证码
|
||||
//// if cc.Captcha == "123456" {
|
||||
//// return nil
|
||||
//// }
|
||||
//// if cc.Captcha == config.AppGlobalConfig.OpenVerifyCode {
|
||||
//// return nil
|
||||
//// }
|
||||
////
|
||||
//// return aduserdb.UpdateVerifyCode(cc, tx)
|
||||
//// }
|
||||
//
|
||||
//// CheckOpenVerifyCode 校验验证码是否免检测验证码,true免检测验证码,false需要检测验证码
|
||||
//func CheckOpenVerifyCode(captcha string) bool {
|
||||
// // TODO 免检测验证码
|
||||
// //if captcha == "123456" {
|
||||
// // return true
|
||||
// //}
|
||||
//
|
||||
// if captcha == config.ExtConfig.OpenVerifyCode {
|
||||
// return true
|
||||
// }
|
||||
// return false
|
||||
//}
|
||||
//
|
||||
//// CheckPhoneOrEmailCaptcha 手机或者邮箱验证码检测
|
||||
//func CheckPhoneOrEmailCaptcha(orm *gorm.DB, phone sysmodel.CheckCaptcha) int {
|
||||
// return CheckCaptchaNew(orm, phone, sysmodel.CheckCaptcha{}, "", "")
|
||||
//}
|
||||
//
|
||||
//// CheckCaptchaNew 校验验证码,1.phone手机验证,2.email邮箱验证,3.googleAuth谷歌验证,也可以只传一个结构体,比如phone验证一个,无需指定是手机或者邮箱
|
||||
//func CheckCaptchaNew(orm *gorm.DB, phone sysmodel.CheckCaptcha, email sysmodel.CheckCaptcha, googleSecret, googleCaptcha string) int {
|
||||
// // TODO 免检测验证码
|
||||
//
|
||||
// var phoneCode models.AdVerifyCode
|
||||
// if len(phone.Captcha) > 0 && !CheckOpenVerifyCode(phone.Captcha) {
|
||||
// // 校验手机号码发送的验证码
|
||||
// phoneCode = aduserdb.GetVerifyCode(orm, phone)
|
||||
// if phoneCode.Id == 0 {
|
||||
// return statuscode.PhoneCaptchaInvalid
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// var emailCode models.AdVerifyCode
|
||||
// if len(email.Captcha) > 0 && !CheckOpenVerifyCode(email.Captcha) {
|
||||
// // 校验邮箱号码发送的验证码
|
||||
// emailCode = aduserdb.GetVerifyCode(orm, email)
|
||||
// if emailCode.Id == 0 {
|
||||
// return statuscode.EmailCaptchaInvalid
|
||||
// }
|
||||
// }
|
||||
// if len(googleCaptcha) > 0 {
|
||||
// // 校验谷歌的验证码
|
||||
// auth := googleauthhelper.VerifyCode(googleSecret, utility.StringAsInt32(googleCaptcha))
|
||||
// if !auth {
|
||||
// return statuscode.GoogleCaptchaInvalid
|
||||
// }
|
||||
// }
|
||||
// // 没手机+邮箱验证,应该只验证谷歌,到这里就返回ok
|
||||
// if phoneCode.Id == 0 && emailCode.Id == 0 {
|
||||
// return statuscode.OK
|
||||
// }
|
||||
//
|
||||
// var transCode int
|
||||
//
|
||||
// // 更新手机+邮箱验证码的数据状态
|
||||
// err := orm.Transaction(func(tx *gorm.DB) (err error) {
|
||||
//
|
||||
// if phoneCode.Id > 0 {
|
||||
// err = aduserdb.UpdateVerifyFlag(orm, phoneCode.Id)
|
||||
// if err != nil {
|
||||
// // _ = tx.Rollback()
|
||||
// transCode = statuscode.PhoneCaptchaInvalid
|
||||
//
|
||||
// return err
|
||||
// }
|
||||
// }
|
||||
// if emailCode.Id > 0 {
|
||||
// err = aduserdb.UpdateVerifyFlag(orm, emailCode.Id)
|
||||
// if err != nil {
|
||||
// // _ = tx.Rollback()
|
||||
// transCode = statuscode.EmailCaptchaInvalid
|
||||
//
|
||||
// return err
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// return nil
|
||||
// })
|
||||
// // tx, err := dbhelper.MasterPgdb.Beginx()
|
||||
// // if err != nil {
|
||||
// // log.Error("Begin", zap.Error(err))
|
||||
// // return statuscode.ServerError
|
||||
// // }
|
||||
// // if phoneCode.Id > 0 {
|
||||
// // err = aduserdb.UpdateVerifyFlag(orm, phoneCode.Id)
|
||||
// // if err != nil {
|
||||
// // _ = tx.Rollback()
|
||||
// // return statuscode.PhoneCaptchaInvalid
|
||||
// // }
|
||||
// // }
|
||||
// // if emailCode.Id > 0 {
|
||||
// // err = aduserdb.UpdateVerifyFlag(orm, emailCode.Id)
|
||||
// // if err != nil {
|
||||
// // _ = tx.Rollback()
|
||||
// // return statuscode.EmailCaptchaInvalid
|
||||
// // }
|
||||
// // }
|
||||
// // _ = tx.Commit()
|
||||
//
|
||||
// if err != nil {
|
||||
// return transCode
|
||||
// }
|
||||
//
|
||||
// return statuscode.OK
|
||||
//}
|
||||
//
|
||||
//// CheckCredentials 校验凭证
|
||||
//func CheckCredentials(req sysmodel.Credential, credentials string) bool {
|
||||
// // 解析得到 Credentials Json
|
||||
// CreJ := aeshelper.Decrypt(credentials, codeVerifySuccess)
|
||||
// if len(CreJ) <= 0 {
|
||||
// log.Error("credentials error")
|
||||
// return false
|
||||
// }
|
||||
//
|
||||
// Cre := sysmodel.Credential{}
|
||||
// _ = sonic.Unmarshal([]byte(CreJ), &Cre)
|
||||
//
|
||||
// // 凭证最长有效时间2分钟
|
||||
// var maxValidTime = int64(2 * time.Minute.Seconds())
|
||||
//
|
||||
// // 逐一比对凭证字段
|
||||
// if Cre.BusinessType != req.BusinessType {
|
||||
// log.Error(fmt.Sprintf("凭证业务类型有误, BusinesType: %d credentialsBusinesType %d", req.BusinessType, Cre.BusinessType))
|
||||
// return false
|
||||
// }
|
||||
//
|
||||
// if Cre.UserID != req.UserID {
|
||||
// log.Error(fmt.Sprintf("凭证用户ID有误, UserID: %d credentialsUserID %d", req.UserID, Cre.UserID))
|
||||
// return false
|
||||
// }
|
||||
//
|
||||
// if len(Cre.Phone) > 0 && Cre.Phone != req.Phone {
|
||||
// log.Error(fmt.Sprintf("凭证手机有误, Phone: %s credentialsPhone %s", req.Phone, Cre.Phone))
|
||||
// return false
|
||||
// }
|
||||
//
|
||||
// if len(Cre.Email) > 0 && Cre.Email != req.Email {
|
||||
// log.Error(fmt.Sprintf("凭证邮箱有误, Email: %s credentialsEmail %s", req.Email, Cre.Email))
|
||||
// return false
|
||||
// }
|
||||
//
|
||||
// if time.Now().Unix() > Cre.Time+maxValidTime {
|
||||
// log.Error(fmt.Sprintf("凭证已过期, 当前时间: %d 凭证过期时间 %d", time.Now().Unix(), Cre.Time+maxValidTime))
|
||||
// return false
|
||||
// }
|
||||
//
|
||||
// return true
|
||||
//}
|
||||
|
||||
func SendGoToneSms(phone, area string) int {
|
||||
//smsCode =
|
||||
smsString := inttostring.GenerateRandomSmsString(6)
|
||||
defer func() {
|
||||
// 使用 recover 来捕获 panic,避免 goroutine 导致程序崩溃
|
||||
if r := recover(); r != nil {
|
||||
log.Error("SendRegisterEmail Error:", r)
|
||||
}
|
||||
}()
|
||||
get := helper.DefaultRedis.Get(fmt.Sprintf("mobile-%s-register", phone))
|
||||
if get.Val() != "" { //说明邮箱操作频繁
|
||||
return statuscode.GoToneSmsOrderTooOften
|
||||
}
|
||||
key := fmt.Sprintf(rediskey.PCRegisterMobile, phone)
|
||||
if err := helper.DefaultRedis.SetStringExpire(key, smsString, time.Second*300); err != nil {
|
||||
log.Error("sendEmail setRedis Error:", zap.Error(err))
|
||||
return statuscode.ServerError
|
||||
}
|
||||
//ext.ExtConfig.GoToneSmsConfig
|
||||
// SmsRequest 用于构建发送短信请求的结构体
|
||||
type SmsRequest struct {
|
||||
Recipient string `json:"recipient"` // 收件人电话号码
|
||||
Message string `json:"message"` // 短信内容
|
||||
SenderId string `json:"sender_id"` // 发送者名称
|
||||
Type string `json:"type"`
|
||||
}
|
||||
// 创建请求数据
|
||||
smsRequest := SmsRequest{
|
||||
Recipient: "+" + area + phone,
|
||||
SenderId: ext.ExtConfig.GoToneSmsConfig.SenderId,
|
||||
Message: fmt.Sprintf("欢迎使用 GoTone SMS,高速稳定地发送短信至中国大陆及全球用户,体验验证码:%s。如非本人操作请忽略此信息", smsString),
|
||||
Type: "plain",
|
||||
}
|
||||
// 将请求数据编码为 JSON
|
||||
requestBody, err := sonic.Marshal(smsRequest)
|
||||
if err != nil {
|
||||
log.Error("GoToneSms requestBody Error:", err)
|
||||
return statuscode.ServerError
|
||||
}
|
||||
// 创建 HTTP 请求
|
||||
req, err := http.NewRequest("POST", ext.ExtConfig.GoToneSmsConfig.APIEndpoint, bytes.NewBuffer(requestBody))
|
||||
if err != nil {
|
||||
log.Error("GoToneSms http.NewRequest Error:", err)
|
||||
return statuscode.ServerError
|
||||
}
|
||||
// 设置请求头
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+ext.ExtConfig.GoToneSmsConfig.Authorization) // 使用 API 密钥进行身份验证
|
||||
|
||||
// 创建 HTTP 客户端并发送请求
|
||||
client := &http.Client{
|
||||
Timeout: 10 * time.Second, // 设置请求超时时间
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
fmt.Println("resp:", resp)
|
||||
if err != nil {
|
||||
log.Error("GoToneSms do NewRequest Error:", err)
|
||||
return statuscode.CaptchaFailInSend
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
// 检查响应状态
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
log.Error("GoToneSms do NewRequest Error:", err)
|
||||
return statuscode.CaptchaFailInSend
|
||||
}
|
||||
// 读取响应体
|
||||
body, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Error("读取响应体失败:", err)
|
||||
fmt.Printf("响应体: %s", string(body))
|
||||
return statuscode.CaptchaFailInSend
|
||||
//return fmt.Errorf("读取响应体失败: %v", err)
|
||||
}
|
||||
// 打印响应内容(调试用)
|
||||
//记录短信发送操作
|
||||
helper.DefaultRedis.SetStringExpire(fmt.Sprintf("mobile-%s-register", phone), "register", time.Second*60)
|
||||
return statuscode.OK
|
||||
}
|
||||
36
common/service/sysservice/authservice/mailjet_test.go
Normal file
36
common/service/sysservice/authservice/mailjet_test.go
Normal file
@ -0,0 +1,36 @@
|
||||
package authservice
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/mailjet/mailjet-apiv3-go"
|
||||
"log"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestName(t *testing.T) {
|
||||
mailjetClient := mailjet.NewMailjetClient("00d2889da90d5d90767bf04dc1bdc6fa", "f68cd84cd88b7e2aabce79c878a77e97")
|
||||
messagesInfo := []mailjet.InfoMessagesV31{
|
||||
{
|
||||
From: &mailjet.RecipientV31{
|
||||
Email: "a745455408@163.com",
|
||||
Name: "Tokex",
|
||||
},
|
||||
To: &mailjet.RecipientsV31{
|
||||
mailjet.RecipientV31{
|
||||
Email: "2811588041@qq.com",
|
||||
Name: "YCZ",
|
||||
},
|
||||
},
|
||||
Subject: "Register/Login",
|
||||
TextPart: "欢迎注册登录我们的服务,您的验证码为:123456",
|
||||
// HTMLPart: "<h3>欢迎注册登录我们的服务,您的验证码为:1234567</h3><br />May the delivery force be with you!",
|
||||
// CustomID: "AppGettingStartedTest",
|
||||
},
|
||||
}
|
||||
messages := mailjet.MessagesV31{Info: messagesInfo}
|
||||
res, err := mailjetClient.SendMailV31(&messages)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
}
|
||||
fmt.Printf("Data: %+v\n", res)
|
||||
}
|
||||
72
common/service/sysservice/sysstatuscode/statuscode.go
Normal file
72
common/service/sysservice/sysstatuscode/statuscode.go
Normal file
@ -0,0 +1,72 @@
|
||||
package sysstatuscode
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"go-admin/app/admin/models/sysmodel"
|
||||
"go-admin/app/admin/service/common"
|
||||
"go-admin/app/admin/service/sysdb"
|
||||
"go-admin/pkg/utility"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var (
|
||||
statusCodeMap = make(map[int]sysmodel.StatusCode)
|
||||
)
|
||||
|
||||
// InitStatusCodeLanguage 初始化状态码语言包
|
||||
func InitStatusCodeLanguage(orm *gorm.DB) {
|
||||
statusCodeList := sysdb.GetAllStatusCode(orm)
|
||||
for _, code := range statusCodeList {
|
||||
statusCodeMap[code.Code] = code
|
||||
}
|
||||
}
|
||||
|
||||
// GetStatusCodeLanguage 获取状态码多语言
|
||||
func GetStatusCodeLanguage(code int, language string) string {
|
||||
c, ok := statusCodeMap[code]
|
||||
if !ok {
|
||||
return utility.IntToString(code)
|
||||
}
|
||||
switch language {
|
||||
case "en":
|
||||
return c.En
|
||||
case "zh-CN":
|
||||
return c.ZhCN
|
||||
case "zh-HK":
|
||||
return c.ZhHK
|
||||
default:
|
||||
return c.Explain
|
||||
}
|
||||
|
||||
//if strings.EqualFold("en", language) {
|
||||
// return c.En
|
||||
//} else if strings.EqualFold("zh-CN", language) {
|
||||
// return c.ZhCN
|
||||
//} else if strings.EqualFold("zh-HK", language) {
|
||||
// return c.ZhHK
|
||||
//} else {
|
||||
// //默认返回
|
||||
// return c.Explain
|
||||
//}
|
||||
}
|
||||
|
||||
func GetStatusCodeDescription(c *gin.Context, code int) string {
|
||||
lang := common.GetLanguage(c)
|
||||
|
||||
return GetStatusCodeLanguage(code, lang)
|
||||
}
|
||||
|
||||
func GetStatusCodeDiscreptionArgs(c *gin.Context, code int, langArg interface{}) string {
|
||||
lang := common.GetLanguage(c)
|
||||
description := GetStatusCodeLanguage(code, lang)
|
||||
|
||||
if _, ok := langArg.(int); ok {
|
||||
description = fmt.Sprintf(description, langArg)
|
||||
} else if _, ok := langArg.(int64); ok {
|
||||
description = fmt.Sprintf(description, langArg)
|
||||
}
|
||||
|
||||
return description
|
||||
}
|
||||
Reference in New Issue
Block a user