Compare commits
7 Commits
2fafcb9bfd
...
feature/em
| Author | SHA1 | Date | |
|---|---|---|---|
| f594a3e9fb | |||
| 135a8151e4 | |||
| 057681561a | |||
| 9876169c84 | |||
| 5371b1d1c6 | |||
| fcd9816b0b | |||
|
|
18597ba7fa |
2
.gitignore
vendored
2
.gitignore
vendored
@@ -7,5 +7,7 @@
|
|||||||
texpixel
|
texpixel
|
||||||
/vendor
|
/vendor
|
||||||
|
|
||||||
|
doc_ai
|
||||||
|
document_ai
|
||||||
dev_deploy.sh
|
dev_deploy.sh
|
||||||
speed_take.sh
|
speed_take.sh
|
||||||
@@ -43,6 +43,7 @@ func SetupRouter(engine *gin.RouterGroup) {
|
|||||||
userRouter := v1.Group("/user")
|
userRouter := v1.Group("/user")
|
||||||
{
|
{
|
||||||
userRouter.POST("/sms", userEndpoint.SendVerificationCode)
|
userRouter.POST("/sms", userEndpoint.SendVerificationCode)
|
||||||
|
userRouter.POST("/email/code", userEndpoint.SendEmailVerifyCode)
|
||||||
userRouter.POST("/register", userEndpoint.RegisterByEmail)
|
userRouter.POST("/register", userEndpoint.RegisterByEmail)
|
||||||
userRouter.POST("/login", userEndpoint.LoginByEmail)
|
userRouter.POST("/login", userEndpoint.LoginByEmail)
|
||||||
userRouter.GET("/oauth/google/url", userEndpoint.GetGoogleOAuthUrl)
|
userRouter.GET("/oauth/google/url", userEndpoint.GetGoogleOAuthUrl)
|
||||||
|
|||||||
@@ -106,6 +106,26 @@ func (h *UserEndpoint) GetUserInfo(ctx *gin.Context) {
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (h *UserEndpoint) SendEmailVerifyCode(ctx *gin.Context) {
|
||||||
|
req := model.EmailVerifyCodeRequest{}
|
||||||
|
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||||
|
ctx.JSON(http.StatusOK, common.ErrorResponse(ctx, common.CodeParamError, common.CodeParamErrorMsg))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := h.userService.SendEmailVerifyCode(ctx, req.Email); err != nil {
|
||||||
|
if bizErr, ok := err.(*common.BusinessError); ok {
|
||||||
|
ctx.JSON(http.StatusOK, common.ErrorResponse(ctx, int(bizErr.Code), bizErr.Message))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
log.Error(ctx, "func", "SendEmailVerifyCode", "msg", "发送邮件验证码失败", "error", err)
|
||||||
|
ctx.JSON(http.StatusOK, common.ErrorResponse(ctx, common.CodeSystemError, common.CodeSystemErrorMsg))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx.JSON(http.StatusOK, common.SuccessResponse(ctx, model.EmailVerifyCodeResponse{}))
|
||||||
|
}
|
||||||
|
|
||||||
func (h *UserEndpoint) RegisterByEmail(ctx *gin.Context) {
|
func (h *UserEndpoint) RegisterByEmail(ctx *gin.Context) {
|
||||||
req := model.EmailRegisterRequest{}
|
req := model.EmailRegisterRequest{}
|
||||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||||
@@ -113,7 +133,7 @@ func (h *UserEndpoint) RegisterByEmail(ctx *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
uid, err := h.userService.RegisterByEmail(ctx, req.Email, req.Password)
|
uid, err := h.userService.RegisterByEmail(ctx, req.Email, req.Password, req.VerifyCode)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if bizErr, ok := err.(*common.BusinessError); ok {
|
if bizErr, ok := err.(*common.BusinessError); ok {
|
||||||
ctx.JSON(http.StatusOK, common.ErrorResponse(ctx, int(bizErr.Code), bizErr.Message))
|
ctx.JSON(http.StatusOK, common.ErrorResponse(ctx, int(bizErr.Code), bizErr.Message))
|
||||||
|
|||||||
@@ -16,6 +16,25 @@ type Config struct {
|
|||||||
Mathpix MathpixConfig `mapstructure:"mathpix"`
|
Mathpix MathpixConfig `mapstructure:"mathpix"`
|
||||||
BaiduOCR BaiduOCRConfig `mapstructure:"baidu_ocr"`
|
BaiduOCR BaiduOCRConfig `mapstructure:"baidu_ocr"`
|
||||||
Google GoogleOAuthConfig `mapstructure:"google"`
|
Google GoogleOAuthConfig `mapstructure:"google"`
|
||||||
|
Email EmailConfig `mapstructure:"email"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type EmailConfig struct {
|
||||||
|
FromName string `mapstructure:"from_name"`
|
||||||
|
FromAddr string `mapstructure:"from_addr"`
|
||||||
|
AliyunSMTP AliyunSMTPConfig `mapstructure:"aliyun_smtp"`
|
||||||
|
Resend ResendEmailConfig `mapstructure:"resend"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type AliyunSMTPConfig struct {
|
||||||
|
Host string `mapstructure:"host"`
|
||||||
|
Port int `mapstructure:"port"`
|
||||||
|
Username string `mapstructure:"username"`
|
||||||
|
Password string `mapstructure:"password"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ResendEmailConfig struct {
|
||||||
|
APIKey string `mapstructure:"api_key"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type BaiduOCRConfig struct {
|
type BaiduOCRConfig struct {
|
||||||
|
|||||||
@@ -7,14 +7,14 @@ database:
|
|||||||
host: localhost
|
host: localhost
|
||||||
port: 3006
|
port: 3006
|
||||||
username: root
|
username: root
|
||||||
password: texpixel#pwd123!
|
password: root123
|
||||||
dbname: doc_ai
|
dbname: doc_ai
|
||||||
max_idle: 10
|
max_idle: 10
|
||||||
max_open: 100
|
max_open: 100
|
||||||
|
|
||||||
redis:
|
redis:
|
||||||
addr: localhost:6079
|
addr: localhost:6079
|
||||||
password: yoge@123321!
|
password: redis123
|
||||||
db: 0
|
db: 0
|
||||||
|
|
||||||
limit:
|
limit:
|
||||||
@@ -56,3 +56,14 @@ google:
|
|||||||
client_secret: "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"
|
client_secret: "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"
|
||||||
redirect_uri: "https://app.cloud.texpixel.com:10443/auth/google/callback"
|
redirect_uri: "https://app.cloud.texpixel.com:10443/auth/google/callback"
|
||||||
proxy: "http://localhost:7890"
|
proxy: "http://localhost:7890"
|
||||||
|
|
||||||
|
email:
|
||||||
|
from_name: "TexPixel Support"
|
||||||
|
from_addr: "support@texpixel.com"
|
||||||
|
aliyun_smtp:
|
||||||
|
host: "smtp.qiye.aliyun.com"
|
||||||
|
port: 465
|
||||||
|
username: "support@texpixel.com"
|
||||||
|
password: "8bPw2W9LlgHSTTfk"
|
||||||
|
resend:
|
||||||
|
api_key: "re_xxxxxxxxxxxx"
|
||||||
|
|||||||
@@ -56,3 +56,14 @@ google:
|
|||||||
client_secret: "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"
|
client_secret: "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"
|
||||||
redirect_uri: "https://texpixel.com/auth/google/callback"
|
redirect_uri: "https://texpixel.com/auth/google/callback"
|
||||||
proxy: "http://100.115.184.74:7890"
|
proxy: "http://100.115.184.74:7890"
|
||||||
|
|
||||||
|
email:
|
||||||
|
from_name: "TexPixel Support"
|
||||||
|
from_addr: "support@texpixel.com"
|
||||||
|
aliyun_smtp:
|
||||||
|
host: "smtp.qiye.aliyun.com"
|
||||||
|
port: 465
|
||||||
|
username: "support@texpixel.com"
|
||||||
|
password: "8bPw2W9LlgHSTTfk"
|
||||||
|
resend:
|
||||||
|
api_key: "re_xxxxxxxxxxxx"
|
||||||
|
|||||||
@@ -1,10 +1,68 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
docker build -t crpi-8s2ierii2xan4klg.cn-beijing.personal.cr.aliyuncs.com/texpixel/doc_ai_backend:latest . && docker push crpi-8s2ierii2xan4klg.cn-beijing.personal.cr.aliyuncs.com/texpixel/doc_ai_backend:latest
|
REGISTRY="crpi-8s2ierii2xan4klg.cn-beijing.personal.cr.aliyuncs.com/texpixel/doc_ai_backend"
|
||||||
|
BUILD_HOST="ubuntu"
|
||||||
|
BUILD_DIR="~/Dev/doc_ai_backed"
|
||||||
|
|
||||||
ssh ecs << 'ENDSSH'
|
# --- Guard: must be on main/master ---
|
||||||
docker stop doc_ai doc_ai_backend 2>/dev/null || true
|
BRANCH=$(git rev-parse --abbrev-ref HEAD)
|
||||||
docker rm doc_ai doc_ai_backend 2>/dev/null || true
|
if [[ "${BRANCH}" != "main" && "${BRANCH}" != "master" ]]; then
|
||||||
docker pull crpi-8s2ierii2xan4klg.cn-beijing.personal.cr.aliyuncs.com/texpixel/doc_ai_backend:latest
|
echo "ERROR: must be on main or master branch (current: ${BRANCH})"
|
||||||
docker run -d --name doc_ai -p 8024:8024 --restart unless-stopped crpi-8s2ierii2xan4klg.cn-beijing.personal.cr.aliyuncs.com/texpixel/doc_ai_backend:latest -env=prod
|
exit 1
|
||||||
ENDSSH
|
fi
|
||||||
|
|
||||||
|
VERSION=$(git rev-parse --short HEAD)
|
||||||
|
IMAGE_VERSIONED="${REGISTRY}:${VERSION}"
|
||||||
|
IMAGE_LATEST="${REGISTRY}:latest"
|
||||||
|
|
||||||
|
echo "==> [1/3] Pulling latest code on Ubuntu"
|
||||||
|
ssh ${BUILD_HOST} "
|
||||||
|
set -e
|
||||||
|
cd ${BUILD_DIR}
|
||||||
|
git fetch origin
|
||||||
|
git checkout master 2>/dev/null || git checkout main
|
||||||
|
git pull
|
||||||
|
"
|
||||||
|
|
||||||
|
echo "==> [2/3] Building & pushing image on Ubuntu"
|
||||||
|
ssh ${BUILD_HOST} "
|
||||||
|
set -e
|
||||||
|
cd ${BUILD_DIR}
|
||||||
|
docker build --platform linux/amd64 \
|
||||||
|
-t ${IMAGE_VERSIONED} \
|
||||||
|
-t ${IMAGE_LATEST} \
|
||||||
|
.
|
||||||
|
docker push ${IMAGE_VERSIONED}
|
||||||
|
docker push ${IMAGE_LATEST}
|
||||||
|
docker rmi ${IMAGE_VERSIONED} ${IMAGE_LATEST} 2>/dev/null || true
|
||||||
|
"
|
||||||
|
|
||||||
|
echo "==> [3/3] Deploying on ECS"
|
||||||
|
ssh ecs "
|
||||||
|
set -e
|
||||||
|
echo '--- Pulling image'
|
||||||
|
docker pull ${IMAGE_VERSIONED}
|
||||||
|
|
||||||
|
echo '--- Stopping old container'
|
||||||
|
docker stop doc_ai 2>/dev/null || true
|
||||||
|
docker rm doc_ai 2>/dev/null || true
|
||||||
|
|
||||||
|
echo '--- Starting new container'
|
||||||
|
docker run -d \
|
||||||
|
--name doc_ai \
|
||||||
|
-p 8024:8024 \
|
||||||
|
--restart unless-stopped \
|
||||||
|
${IMAGE_VERSIONED} \
|
||||||
|
-env=prod
|
||||||
|
|
||||||
|
echo '--- Removing old doc_ai images (keeping current)'
|
||||||
|
docker images --format '{{.Repository}}:{{.Tag}} {{.ID}}' \
|
||||||
|
| grep '^${REGISTRY}' \
|
||||||
|
| grep -v ':${VERSION}' \
|
||||||
|
| grep -v ':latest' \
|
||||||
|
| awk '{print \$2}' \
|
||||||
|
| xargs -r docker rmi || true
|
||||||
|
"
|
||||||
|
|
||||||
|
echo "==> Done. Running version: ${VERSION}"
|
||||||
|
|||||||
@@ -23,9 +23,16 @@ type UserInfoResponse struct {
|
|||||||
Email string `json:"email"`
|
Email string `json:"email"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type EmailVerifyCodeRequest struct {
|
||||||
|
Email string `json:"email" binding:"required,email"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type EmailVerifyCodeResponse struct{}
|
||||||
|
|
||||||
type EmailRegisterRequest struct {
|
type EmailRegisterRequest struct {
|
||||||
Email string `json:"email" binding:"required,email"`
|
Email string `json:"email" binding:"required,email"`
|
||||||
Password string `json:"password" binding:"required,min=6"`
|
Password string `json:"password" binding:"required,min=6"`
|
||||||
|
VerifyCode string `json:"verify_code" binding:"required"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type EmailRegisterResponse struct {
|
type EmailRegisterResponse struct {
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
"gitea.com/texpixel/document_ai/internal/model/task"
|
"gitea.com/texpixel/document_ai/internal/model/task"
|
||||||
"gitea.com/texpixel/document_ai/internal/storage/dao"
|
"gitea.com/texpixel/document_ai/internal/storage/dao"
|
||||||
@@ -187,7 +188,13 @@ func (svc *TaskService) ExportTask(ctx context.Context, req *task.ExportTaskRequ
|
|||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
|
|
||||||
if resp.StatusCode != http.StatusOK {
|
if resp.StatusCode != http.StatusOK {
|
||||||
log.Error(ctx, "func", "ExportTask", "msg", "http request failed", "status", resp.StatusCode)
|
respBody, _ := io.ReadAll(resp.Body)
|
||||||
|
log.Error(ctx, "func", "ExportTask", "msg", "export service returned non-200",
|
||||||
|
"status", resp.StatusCode,
|
||||||
|
"body", string(respBody),
|
||||||
|
"markdown_len", len(markdown),
|
||||||
|
"filename", filename,
|
||||||
|
)
|
||||||
return nil, "", fmt.Errorf("export service returned status: %d", resp.StatusCode)
|
return nil, "", fmt.Errorf("export service returned status: %d", resp.StatusCode)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import (
|
|||||||
"gitea.com/texpixel/document_ai/internal/storage/cache"
|
"gitea.com/texpixel/document_ai/internal/storage/cache"
|
||||||
"gitea.com/texpixel/document_ai/internal/storage/dao"
|
"gitea.com/texpixel/document_ai/internal/storage/dao"
|
||||||
"gitea.com/texpixel/document_ai/pkg/common"
|
"gitea.com/texpixel/document_ai/pkg/common"
|
||||||
|
"gitea.com/texpixel/document_ai/pkg/email"
|
||||||
"gitea.com/texpixel/document_ai/pkg/log"
|
"gitea.com/texpixel/document_ai/pkg/log"
|
||||||
"gitea.com/texpixel/document_ai/pkg/sms"
|
"gitea.com/texpixel/document_ai/pkg/sms"
|
||||||
"golang.org/x/crypto/bcrypt"
|
"golang.org/x/crypto/bcrypt"
|
||||||
@@ -115,14 +116,57 @@ func (svc *UserService) GetUserInfo(ctx context.Context, uid int64) (*dao.User,
|
|||||||
return user, nil
|
return user, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (svc *UserService) RegisterByEmail(ctx context.Context, email, password string) (uid int64, err error) {
|
func (svc *UserService) SendEmailVerifyCode(ctx context.Context, emailAddr string) error {
|
||||||
existingUser, err := svc.userDao.GetByEmail(dao.DB.WithContext(ctx), email)
|
limit, err := cache.GetUserSendEmailLimit(ctx, emailAddr)
|
||||||
|
if err != nil {
|
||||||
|
log.Error(ctx, "func", "SendEmailVerifyCode", "msg", "get send email limit error", "error", err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if limit >= cache.UserSendEmailLimitCount {
|
||||||
|
return common.ErrEmailSendLimit
|
||||||
|
}
|
||||||
|
|
||||||
|
code := fmt.Sprintf("%06d", rand.Intn(1000000))
|
||||||
|
|
||||||
|
subject := "Your verification code"
|
||||||
|
body := fmt.Sprintf("Your verification code is: %s\nIt will expire in 10 minutes.", code)
|
||||||
|
if err := email.Send(ctx, emailAddr, subject, body); err != nil {
|
||||||
|
log.Error(ctx, "func", "SendEmailVerifyCode", "msg", "send email error", "error", err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if cacheErr := cache.SetUserEmailCode(ctx, emailAddr, code); cacheErr != nil {
|
||||||
|
log.Error(ctx, "func", "SendEmailVerifyCode", "msg", "set email code error", "error", cacheErr)
|
||||||
|
}
|
||||||
|
if cacheErr := cache.SetUserSendEmailLimit(ctx, emailAddr); cacheErr != nil {
|
||||||
|
log.Error(ctx, "func", "SendEmailVerifyCode", "msg", "set send email limit error", "error", cacheErr)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (svc *UserService) RegisterByEmail(ctx context.Context, emailAddr, password, verifyCode string) (uid int64, err error) {
|
||||||
|
storedCode, err := cache.GetUserEmailCode(ctx, emailAddr)
|
||||||
|
if err != nil {
|
||||||
|
log.Error(ctx, "func", "RegisterByEmail", "msg", "get email code error", "error", err)
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
if storedCode == "" || storedCode != verifyCode {
|
||||||
|
return 0, common.ErrEmailCodeError
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = cache.DeleteUserEmailCode(ctx, emailAddr)
|
||||||
|
|
||||||
|
return svc.registerByEmailInternal(ctx, emailAddr, password)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (svc *UserService) registerByEmailInternal(ctx context.Context, emailAddr, password string) (uid int64, err error) {
|
||||||
|
existingUser, err := svc.userDao.GetByEmail(dao.DB.WithContext(ctx), emailAddr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error(ctx, "func", "RegisterByEmail", "msg", "get user by email error", "error", err)
|
log.Error(ctx, "func", "RegisterByEmail", "msg", "get user by email error", "error", err)
|
||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
if existingUser != nil {
|
if existingUser != nil {
|
||||||
log.Warn(ctx, "func", "RegisterByEmail", "msg", "email already registered", "email", email)
|
log.Warn(ctx, "func", "RegisterByEmail", "msg", "email already registered", "email", emailAddr)
|
||||||
return 0, common.ErrEmailExists
|
return 0, common.ErrEmailExists
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -133,7 +177,7 @@ func (svc *UserService) RegisterByEmail(ctx context.Context, email, password str
|
|||||||
}
|
}
|
||||||
|
|
||||||
user := &dao.User{
|
user := &dao.User{
|
||||||
Email: email,
|
Email: emailAddr,
|
||||||
Password: string(hashedPassword),
|
Password: string(hashedPassword),
|
||||||
}
|
}
|
||||||
err = svc.userDao.Create(dao.DB.WithContext(ctx), user)
|
err = svc.userDao.Create(dao.DB.WithContext(ctx), user)
|
||||||
|
|||||||
52
internal/storage/cache/user.go
vendored
52
internal/storage/cache/user.go
vendored
@@ -61,3 +61,55 @@ func SetUserSendSmsLimit(ctx context.Context, phone string) error {
|
|||||||
func DeleteUserSmsCode(ctx context.Context, phone string) error {
|
func DeleteUserSmsCode(ctx context.Context, phone string) error {
|
||||||
return RedisClient.Del(ctx, fmt.Sprintf(UserSmsCodePrefix, phone)).Err()
|
return RedisClient.Del(ctx, fmt.Sprintf(UserSmsCodePrefix, phone)).Err()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
UserEmailCodeTTL = 10 * time.Minute
|
||||||
|
UserSendEmailLimitTTL = 24 * time.Hour
|
||||||
|
UserSendEmailLimitCount = 5
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
UserEmailCodePrefix = "user:email_code:%s"
|
||||||
|
UserSendEmailLimit = "user:send_email_limit:%s"
|
||||||
|
)
|
||||||
|
|
||||||
|
func GetUserEmailCode(ctx context.Context, email string) (string, error) {
|
||||||
|
code, err := RedisClient.Get(ctx, fmt.Sprintf(UserEmailCodePrefix, email)).Result()
|
||||||
|
if err != nil {
|
||||||
|
if err == redis.Nil {
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return code, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func SetUserEmailCode(ctx context.Context, email, code string) error {
|
||||||
|
return RedisClient.Set(ctx, fmt.Sprintf(UserEmailCodePrefix, email), code, UserEmailCodeTTL).Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetUserSendEmailLimit(ctx context.Context, email string) (int, error) {
|
||||||
|
limit, err := RedisClient.Get(ctx, fmt.Sprintf(UserSendEmailLimit, email)).Result()
|
||||||
|
if err != nil {
|
||||||
|
if err == redis.Nil {
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return strconv.Atoi(limit)
|
||||||
|
}
|
||||||
|
|
||||||
|
func SetUserSendEmailLimit(ctx context.Context, email string) error {
|
||||||
|
count, err := RedisClient.Incr(ctx, fmt.Sprintf(UserSendEmailLimit, email)).Result()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if count > UserSendEmailLimitCount {
|
||||||
|
return errors.New("send email limit")
|
||||||
|
}
|
||||||
|
return RedisClient.Expire(ctx, fmt.Sprintf(UserSendEmailLimit, email), UserSendEmailLimitTTL).Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
func DeleteUserEmailCode(ctx context.Context, email string) error {
|
||||||
|
return RedisClient.Del(ctx, fmt.Sprintf(UserEmailCodePrefix, email)).Err()
|
||||||
|
}
|
||||||
|
|||||||
2
main.go
2
main.go
@@ -16,6 +16,7 @@ import (
|
|||||||
"gitea.com/texpixel/document_ai/internal/storage/dao"
|
"gitea.com/texpixel/document_ai/internal/storage/dao"
|
||||||
"gitea.com/texpixel/document_ai/pkg/common"
|
"gitea.com/texpixel/document_ai/pkg/common"
|
||||||
"gitea.com/texpixel/document_ai/pkg/cors"
|
"gitea.com/texpixel/document_ai/pkg/cors"
|
||||||
|
"gitea.com/texpixel/document_ai/pkg/email"
|
||||||
"gitea.com/texpixel/document_ai/pkg/log"
|
"gitea.com/texpixel/document_ai/pkg/log"
|
||||||
"gitea.com/texpixel/document_ai/pkg/middleware"
|
"gitea.com/texpixel/document_ai/pkg/middleware"
|
||||||
"gitea.com/texpixel/document_ai/pkg/sms"
|
"gitea.com/texpixel/document_ai/pkg/sms"
|
||||||
@@ -44,6 +45,7 @@ func main() {
|
|||||||
dao.InitDB(config.GlobalConfig.Database)
|
dao.InitDB(config.GlobalConfig.Database)
|
||||||
cache.InitRedisClient(config.GlobalConfig.Redis)
|
cache.InitRedisClient(config.GlobalConfig.Redis)
|
||||||
sms.InitSmsClient()
|
sms.InitSmsClient()
|
||||||
|
email.InitEmailClient()
|
||||||
|
|
||||||
// 设置gin模式
|
// 设置gin模式
|
||||||
gin.SetMode(config.GlobalConfig.Server.Mode)
|
gin.SetMode(config.GlobalConfig.Server.Mode)
|
||||||
|
|||||||
@@ -18,6 +18,8 @@ const (
|
|||||||
CodeEmailExists = 1004
|
CodeEmailExists = 1004
|
||||||
CodeEmailNotFound = 1005
|
CodeEmailNotFound = 1005
|
||||||
CodePasswordMismatch = 1006
|
CodePasswordMismatch = 1006
|
||||||
|
CodeEmailCodeError = 1007
|
||||||
|
CodeEmailSendLimit = 1008
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -36,6 +38,8 @@ const (
|
|||||||
CodeEmailExistsMsg = "email already registered"
|
CodeEmailExistsMsg = "email already registered"
|
||||||
CodeEmailNotFoundMsg = "email not found"
|
CodeEmailNotFoundMsg = "email not found"
|
||||||
CodePasswordMismatchMsg = "password mismatch"
|
CodePasswordMismatchMsg = "password mismatch"
|
||||||
|
CodeEmailCodeErrorMsg = "email verify code error"
|
||||||
|
CodeEmailSendLimitMsg = "email send limit reached"
|
||||||
)
|
)
|
||||||
|
|
||||||
type BusinessError struct {
|
type BusinessError struct {
|
||||||
@@ -61,4 +65,6 @@ var (
|
|||||||
ErrEmailExists = NewError(CodeEmailExists, CodeEmailExistsMsg, nil)
|
ErrEmailExists = NewError(CodeEmailExists, CodeEmailExistsMsg, nil)
|
||||||
ErrEmailNotFound = NewError(CodeEmailNotFound, CodeEmailNotFoundMsg, nil)
|
ErrEmailNotFound = NewError(CodeEmailNotFound, CodeEmailNotFoundMsg, nil)
|
||||||
ErrPasswordMismatch = NewError(CodePasswordMismatch, CodePasswordMismatchMsg, nil)
|
ErrPasswordMismatch = NewError(CodePasswordMismatch, CodePasswordMismatchMsg, nil)
|
||||||
|
ErrEmailCodeError = NewError(CodeEmailCodeError, CodeEmailCodeErrorMsg, nil)
|
||||||
|
ErrEmailSendLimit = NewError(CodeEmailSendLimit, CodeEmailSendLimitMsg, nil)
|
||||||
)
|
)
|
||||||
|
|||||||
160
pkg/email/email.go
Normal file
160
pkg/email/email.go
Normal file
@@ -0,0 +1,160 @@
|
|||||||
|
package email
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"crypto/tls"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/mail"
|
||||||
|
"net/smtp"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"gitea.com/texpixel/document_ai/config"
|
||||||
|
"gitea.com/texpixel/document_ai/pkg/log"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
once sync.Once
|
||||||
|
client *Client
|
||||||
|
)
|
||||||
|
|
||||||
|
// chineseDomainRe matches email domains that should be routed via Aliyun SMTP.
|
||||||
|
var chineseDomainRe = regexp.MustCompile(`(?i)(\.edu\.cn|qq\.com|163\.com|126\.com|sina\.com|sohu\.com)$`)
|
||||||
|
|
||||||
|
type Client struct {
|
||||||
|
cfg config.EmailConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
func InitEmailClient() *Client {
|
||||||
|
once.Do(func() {
|
||||||
|
client = &Client{cfg: config.GlobalConfig.Email}
|
||||||
|
})
|
||||||
|
return client
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send routes the email to the appropriate provider based on the recipient domain.
|
||||||
|
func Send(ctx context.Context, to, subject, body string) error {
|
||||||
|
if client == nil {
|
||||||
|
return fmt.Errorf("email client not initialized, call InitEmailClient first")
|
||||||
|
}
|
||||||
|
return client.Send(ctx, to, subject, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) Send(ctx context.Context, to, subject, body string) error {
|
||||||
|
if _, err := mail.ParseAddress(to); err != nil {
|
||||||
|
return fmt.Errorf("invalid email address %q: %w", to, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
domain := to[strings.LastIndex(to, "@")+1:]
|
||||||
|
if chineseDomainRe.MatchString(domain) {
|
||||||
|
return c.sendViaAliyunSMTP(ctx, to, subject, body)
|
||||||
|
}
|
||||||
|
return c.sendViaResend(ctx, to, subject, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) sendViaAliyunSMTP(ctx context.Context, to, subject, body string) error {
|
||||||
|
cfg := c.cfg.AliyunSMTP
|
||||||
|
addr := fmt.Sprintf("%s:%d", cfg.Host, cfg.Port)
|
||||||
|
|
||||||
|
tlsConfig := &tls.Config{ServerName: cfg.Host}
|
||||||
|
conn, err := tls.Dial("tcp", addr, tlsConfig)
|
||||||
|
if err != nil {
|
||||||
|
log.Error(ctx, "func", "sendViaAliyunSMTP", "msg", "tls dial failed", "error", err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
smtpClient, err := smtp.NewClient(conn, cfg.Host)
|
||||||
|
if err != nil {
|
||||||
|
conn.Close()
|
||||||
|
log.Error(ctx, "func", "sendViaAliyunSMTP", "msg", "smtp new client failed", "error", err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer smtpClient.Close()
|
||||||
|
|
||||||
|
auth := smtp.PlainAuth("", cfg.Username, cfg.Password, cfg.Host)
|
||||||
|
if err = smtpClient.Auth(auth); err != nil {
|
||||||
|
log.Error(ctx, "func", "sendViaAliyunSMTP", "msg", "smtp auth failed", "error", err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
from := c.cfg.FromAddr
|
||||||
|
if err = smtpClient.Mail(from); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err = smtpClient.Rcpt(to); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
wc, err := smtpClient.Data()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer wc.Close()
|
||||||
|
|
||||||
|
if _, err = wc.Write([]byte(buildMessage(c.cfg.FromName, from, to, subject, body))); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Info(ctx, "func", "sendViaAliyunSMTP", "msg", "email sent via aliyun smtp", "to", to)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type resendRequest struct {
|
||||||
|
From string `json:"from"`
|
||||||
|
To []string `json:"to"`
|
||||||
|
Subject string `json:"subject"`
|
||||||
|
Html string `json:"html"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) sendViaResend(ctx context.Context, to, subject, body string) error {
|
||||||
|
payload := resendRequest{
|
||||||
|
From: fmt.Sprintf("%s <%s>", c.cfg.FromName, c.cfg.FromAddr),
|
||||||
|
To: []string{to},
|
||||||
|
Subject: subject,
|
||||||
|
Html: body,
|
||||||
|
}
|
||||||
|
jsonData, err := json.Marshal(payload)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://api.resend.com/emails", bytes.NewReader(jsonData))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
req.Header.Set("Authorization", "Bearer "+c.cfg.Resend.APIKey)
|
||||||
|
|
||||||
|
resp, err := (&http.Client{}).Do(req)
|
||||||
|
if err != nil {
|
||||||
|
log.Error(ctx, "func", "sendViaResend", "msg", "http request failed", "error", err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
|
||||||
|
respBody, _ := io.ReadAll(io.LimitReader(resp.Body, 1024))
|
||||||
|
log.Error(ctx, "func", "sendViaResend", "msg", "resend api returned non-2xx", "status", resp.StatusCode, "to", to, "body", string(respBody))
|
||||||
|
return fmt.Errorf("resend api returned status %d: %s", resp.StatusCode, string(respBody))
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Info(ctx, "func", "sendViaResend", "msg", "email sent via resend", "to", to)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildMessage(fromName, fromAddr, to, subject, body string) string {
|
||||||
|
var buf bytes.Buffer
|
||||||
|
buf.WriteString(fmt.Sprintf("From: %s <%s>\r\n", fromName, fromAddr))
|
||||||
|
buf.WriteString(fmt.Sprintf("To: %s\r\n", to))
|
||||||
|
buf.WriteString(fmt.Sprintf("Subject: %s\r\n", subject))
|
||||||
|
buf.WriteString("MIME-Version: 1.0\r\n")
|
||||||
|
buf.WriteString("Content-Type: text/html; charset=UTF-8\r\n")
|
||||||
|
buf.WriteString("\r\n")
|
||||||
|
buf.WriteString(body)
|
||||||
|
return buf.String()
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user