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>
This commit is contained in:
@@ -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))
|
||||||
|
|||||||
@@ -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 {
|
||||||
|
|||||||
@@ -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()
|
||||||
|
}
|
||||||
|
|||||||
@@ -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)
|
||||||
)
|
)
|
||||||
|
|||||||
Reference in New Issue
Block a user