14 Commits

Author SHA1 Message Date
876e64366b feat: upgrade verification code email with bilingual HTML template
- Chinese domains (qq.com, 163.com, etc.) receive a Chinese email
- All other domains receive an English email
- Prominent code display: 40px monospace with wide letter-spacing
- Clean OpenAI-inspired layout with dark header and card design

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-30 14:44:17 +08:00
87bee98049 feat: add email_send_log table to track email sends and registration status
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-30 14:29:30 +08:00
a07e08a761 fix: change register verify_code field to code to match frontend
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-27 10:05:51 +08:00
f6ccadbcd3 refactor: move deploy scripts into .claude/skills/deploy/
- Added deploy skill (SKILL.md) with dev/prod instructions
- Moved deploy_prod.sh, deploy_dev.sh, dev_deploy.sh, speed_take.sh
- Updated settings.local.json: new script paths, git merge/push permissions, auto-deploy hook on merge to master
- Removed dev_deploy.sh and speed_take.sh from .gitignore

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-27 10:04:41 +08:00
fa1fbfc0f5 fix: set resend api key in prod config
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-27 09:55:13 +08:00
4f468caedf Merge branch 'feature/email_service_optimize' into master 2026-03-27 09:50:32 +08:00
f594a3e9fb feat: add email verify code endpoint and require code on register
- POST /v1/user/email/code sends a 6-digit verify code via email (rate-limited, 10min TTL)
- RegisterByEmail now validates verify_code before creating the account
- Added email code cache helpers mirroring SMS pattern
- Added error codes 1007 (email code error) and 1008 (send limit)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-27 09:50:23 +08:00
e538553045 fix: remove unused time import in task.go
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-27 02:41:40 +08:00
135a8151e4 feat: rm binary file 2026-03-27 02:29:28 +08:00
057681561a feat: update pwd dev env 2026-03-27 02:27:48 +08:00
9876169c84 refactor: optimize email 2026-03-27 01:23:01 +08:00
5371b1d1c6 feat: add dual-engine email service with aliyun smtp and resend routing
Route Chinese domains (edu.cn, qq.com, 163.com, etc.) via Aliyun SMTP
and international addresses via Resend API.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-25 18:33:17 +08:00
fcd9816b0b refact: add log for export 2026-03-25 18:28:12 +08:00
liuyuanchuang
18597ba7fa feat: add log for export error 2026-03-12 11:43:26 +08:00
22 changed files with 714 additions and 24 deletions

View File

@@ -0,0 +1,40 @@
---
name: deploy
description: Use when deploying this project to dev or prod environments, or when asked to run, ship, release, or push to a server.
---
# Deploy
## Environments
### Dev (`/deploy dev`)
```bash
bash .claude/skills/deploy/deploy_dev.sh
```
Builds and restarts the service on the dev server (ubuntu).
### Prod (`/deploy prod`)
Prod deploy requires being on `master`. Steps:
1. Ensure all changes are committed and pushed to `master`
2. Run:
```bash
bash .claude/skills/deploy/deploy_prod.sh
```
`deploy_prod.sh` will:
- Pull latest code on ubuntu build host
- Build `linux/amd64` Docker image and push to registry
- SSH into ECS: stop old container, start new one with `-env=prod`
## Quick Reference
| Target | Command | Branch required |
|--------|---------|-----------------|
| Dev | `bash .claude/skills/deploy/deploy_dev.sh` | any |
| Prod | `bash .claude/skills/deploy/deploy_prod.sh` | `master` or `main` |
## Common Mistakes
- Running `deploy_prod.sh` on a feature branch → script guards against this (exits with error)
- Forgetting to merge/push before deploy → ubuntu build host pulls from remote, so local-only commits won't be included
- Prod logs go to `/app/logs/app.log` inside the container, not stdout — use `docker exec doc_ai tail -f /app/logs/app.log` on ECS to tail them

View File

@@ -0,0 +1,68 @@
#!/bin/bash
set -euo pipefail
REGISTRY="crpi-8s2ierii2xan4klg.cn-beijing.personal.cr.aliyuncs.com/texpixel/doc_ai_backend"
BUILD_HOST="ubuntu"
BUILD_DIR="~/Dev/doc_ai_backed"
# --- Guard: must be on main/master ---
BRANCH=$(git rev-parse --abbrev-ref HEAD)
if [[ "${BRANCH}" != "main" && "${BRANCH}" != "master" ]]; then
echo "ERROR: must be on main or master branch (current: ${BRANCH})"
exit 1
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}"

View File

@@ -0,0 +1,3 @@
docker-compose down
docker image rm doc_ai_backed-doc_ai
docker-compose up -d

View File

@@ -0,0 +1,7 @@
#!/bin/bash
echo "=== Testing 401 Request Speed ==="
curl -X POST "https://api.mathpix.com/v3/text" \
-H "Content-Type: application/json" \
--data '{}' \
-w "\n\n=== Timing ===\nHTTP Status: %{http_code}\nTotal: %{time_total}s\nConnect: %{time_connect}s\nDNS: %{time_namelookup}s\nTTFB: %{time_starttransfer}s\n"

4
.gitignore vendored
View File

@@ -7,5 +7,5 @@
texpixel texpixel
/vendor /vendor
dev_deploy.sh doc_ai
speed_take.sh document_ai

View File

@@ -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)

View File

@@ -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))

View File

@@ -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 {

View File

@@ -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"

View File

@@ -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_dZxRaFAB_D5YME7u6kdRmDxqw4v1G7t87"

View File

@@ -1,10 +0,0 @@
#!/bin/bash
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
ssh ecs << 'ENDSSH'
docker stop doc_ai doc_ai_backend 2>/dev/null || true
docker rm doc_ai doc_ai_backend 2>/dev/null || true
docker pull crpi-8s2ierii2xan4klg.cn-beijing.personal.cr.aliyuncs.com/texpixel/doc_ai_backend:latest
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
ENDSSH

View File

@@ -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:"code" binding:"required"`
} }
type EmailRegisterResponse struct { type EmailRegisterResponse struct {

View File

@@ -187,7 +187,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)
} }

View File

@@ -14,18 +14,21 @@ 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"
) )
type UserService struct { type UserService struct {
userDao *dao.UserDao userDao *dao.UserDao
emailSendLogDao *dao.EmailSendLogDao
} }
func NewUserService() *UserService { func NewUserService() *UserService {
return &UserService{ return &UserService{
userDao: dao.NewUserDao(), userDao: dao.NewUserDao(),
emailSendLogDao: dao.NewEmailSendLogDao(),
} }
} }
@@ -115,14 +118,71 @@ 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, body := email.BuildVerifyCodeEmail(emailAddr, 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)
}
record := &dao.EmailSendLog{Email: emailAddr, Status: dao.EmailSendStatusSent}
if logErr := svc.emailSendLogDao.Create(dao.DB.WithContext(ctx), record); logErr != nil {
log.Error(ctx, "func", "SendEmailVerifyCode", "msg", "create email send log error", "error", logErr)
}
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)
uid, err = svc.registerByEmailInternal(ctx, emailAddr, password)
if err != nil {
return 0, err
}
if logErr := svc.emailSendLogDao.MarkRegistered(dao.DB.WithContext(ctx), emailAddr); logErr != nil {
log.Error(ctx, "func", "RegisterByEmail", "msg", "mark email send log registered error", "error", logErr)
}
return uid, nil
}
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 +193,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)

View File

@@ -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()
}

View File

@@ -0,0 +1,50 @@
package dao
import (
"gorm.io/gorm"
)
type EmailSendStatus int8
const (
EmailSendStatusSent EmailSendStatus = 0 // 已发送,用户未注册
EmailSendStatusRegistered EmailSendStatus = 1 // 用户已完成注册
)
type EmailSendLog struct {
BaseModel
Email string `gorm:"column:email;type:varchar(255);not null;comment:邮箱地址" json:"email"`
Status EmailSendStatus `gorm:"column:status;type:tinyint;not null;default:0;comment:状态: 0=已发送未注册 1=已注册" json:"status"`
}
func (e *EmailSendLog) TableName() string {
return "email_send_log"
}
type EmailSendLogDao struct{}
func NewEmailSendLogDao() *EmailSendLogDao {
return &EmailSendLogDao{}
}
func (d *EmailSendLogDao) Create(tx *gorm.DB, log *EmailSendLog) error {
return tx.Create(log).Error
}
func (d *EmailSendLogDao) GetLatestByEmail(tx *gorm.DB, email string) (*EmailSendLog, error) {
var record EmailSendLog
err := tx.Where("email = ?", email).Order("id DESC").First(&record).Error
if err != nil {
if err == gorm.ErrRecordNotFound {
return nil, nil
}
return nil, err
}
return &record, nil
}
func (d *EmailSendLogDao) MarkRegistered(tx *gorm.DB, email string) error {
return tx.Model(&EmailSendLog{}).
Where("email = ? AND status = ?", email, EmailSendStatusSent).
Update("status", EmailSendStatusRegistered).Error
}

View File

@@ -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)

View File

@@ -0,0 +1,11 @@
CREATE TABLE IF NOT EXISTS `email_send_log` (
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`email` VARCHAR(255) NOT NULL COMMENT '邮箱地址',
`status` TINYINT NOT NULL DEFAULT 0 COMMENT '状态: 0=已发送未注册, 1=已注册',
`created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
INDEX `idx_email` (`email`),
INDEX `idx_status` (`status`),
INDEX `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='邮件发送记录表';

View File

@@ -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
View 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()
}

166
pkg/email/template.go Normal file
View File

@@ -0,0 +1,166 @@
package email
import "fmt"
// BuildVerifyCodeEmail returns a locale-appropriate subject and HTML body for
// the verification code email. Chinese domains get a Chinese email; all others
// get an English one.
func BuildVerifyCodeEmail(toEmail, code string) (subject, body string) {
domain := toEmail[lastIndex(toEmail, '@')+1:]
if chineseDomainRe.MatchString(domain) {
return buildVerifyCodeZH(code)
}
return buildVerifyCodeEN(code)
}
func buildVerifyCodeZH(code string) (subject, body string) {
subject = "您的验证码"
body = fmt.Sprintf(`<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>验证码</title>
</head>
<body style="margin:0;padding:0;background:#f4f4f5;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;">
<table width="100%%" cellpadding="0" cellspacing="0" style="background:#f4f4f5;padding:40px 0;">
<tr>
<td align="center">
<table width="480" cellpadding="0" cellspacing="0" style="background:#ffffff;border-radius:12px;overflow:hidden;box-shadow:0 1px 4px rgba(0,0,0,.08);">
<!-- Header -->
<tr>
<td style="background:#0a0a0a;padding:32px 40px;">
<span style="color:#ffffff;font-size:20px;font-weight:700;letter-spacing:-0.3px;">TexPixel</span>
</td>
</tr>
<!-- Body -->
<tr>
<td style="padding:40px 40px 32px;">
<p style="margin:0 0 8px;font-size:24px;font-weight:700;color:#0a0a0a;line-height:1.3;">验证您的邮箱</p>
<p style="margin:0 0 32px;font-size:15px;color:#6b7280;line-height:1.6;">
请使用以下验证码完成注册。验证码仅对您本人有效,请勿分享给他人。
</p>
<!-- Code block -->
<table width="100%%" cellpadding="0" cellspacing="0">
<tr>
<td align="center" style="background:#f9fafb;border:1px solid #e5e7eb;border-radius:8px;padding:28px 0;">
<span style="font-size:40px;font-weight:700;letter-spacing:12px;color:#0a0a0a;font-family:'Courier New',Courier,monospace;">%s</span>
</td>
</tr>
</table>
<p style="margin:24px 0 0;font-size:13px;color:#9ca3af;text-align:center;">
验证码 <strong>10 分钟</strong>内有效,请尽快使用
</p>
</td>
</tr>
<!-- Divider -->
<tr>
<td style="padding:0 40px;">
<div style="height:1px;background:#f3f4f6;"></div>
</td>
</tr>
<!-- Footer -->
<tr>
<td style="padding:24px 40px 32px;">
<p style="margin:0;font-size:12px;color:#9ca3af;line-height:1.7;">
如果您没有请求此验证码,可以忽略本邮件,您的账户仍然安全。<br/>
&copy; 2025 TexPixel. 保留所有权利。
</p>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>`, code)
return
}
func buildVerifyCodeEN(code string) (subject, body string) {
subject = "Your verification code"
body = fmt.Sprintf(`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Verification Code</title>
</head>
<body style="margin:0;padding:0;background:#f4f4f5;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;">
<table width="100%%" cellpadding="0" cellspacing="0" style="background:#f4f4f5;padding:40px 0;">
<tr>
<td align="center">
<table width="480" cellpadding="0" cellspacing="0" style="background:#ffffff;border-radius:12px;overflow:hidden;box-shadow:0 1px 4px rgba(0,0,0,.08);">
<!-- Header -->
<tr>
<td style="background:#0a0a0a;padding:32px 40px;">
<span style="color:#ffffff;font-size:20px;font-weight:700;letter-spacing:-0.3px;">TexPixel</span>
</td>
</tr>
<!-- Body -->
<tr>
<td style="padding:40px 40px 32px;">
<p style="margin:0 0 8px;font-size:24px;font-weight:700;color:#0a0a0a;line-height:1.3;">Verify your email address</p>
<p style="margin:0 0 32px;font-size:15px;color:#6b7280;line-height:1.6;">
Use the verification code below to complete your registration. Never share this code with anyone.
</p>
<!-- Code block -->
<table width="100%%" cellpadding="0" cellspacing="0">
<tr>
<td align="center" style="background:#f9fafb;border:1px solid #e5e7eb;border-radius:8px;padding:28px 0;">
<span style="font-size:40px;font-weight:700;letter-spacing:12px;color:#0a0a0a;font-family:'Courier New',Courier,monospace;">%s</span>
</td>
</tr>
</table>
<p style="margin:24px 0 0;font-size:13px;color:#9ca3af;text-align:center;">
This code expires in <strong>10 minutes</strong>
</p>
</td>
</tr>
<!-- Divider -->
<tr>
<td style="padding:0 40px;">
<div style="height:1px;background:#f3f4f6;"></div>
</td>
</tr>
<!-- Footer -->
<tr>
<td style="padding:24px 40px 32px;">
<p style="margin:0;font-size:12px;color:#9ca3af;line-height:1.7;">
If you didn&rsquo;t request this code, you can safely ignore this email. Your account is still secure.<br/>
&copy; 2025 TexPixel. All rights reserved.
</p>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>`, code)
return
}
// lastIndex returns the last index of sep in s, or -1.
func lastIndex(s string, sep byte) int {
for i := len(s) - 1; i >= 0; i-- {
if s[i] == sep {
return i
}
}
return -1
}