移动端和 PC 端登录页都加了“图形验证码
This commit is contained in:
@@ -37,7 +37,7 @@ LOG_DIR=/app/logs
|
||||
LOG_ENABLE_CONSOLE=true
|
||||
LOG_ENABLE_FILE=true
|
||||
|
||||
# MinIO 容器初始化变量,同时供后端对象存储使用。
|
||||
# MinIO 容器初始化变量,同时供后端对象存储使用;使用内置 MinIO 时,STORAGE_* 密钥必须和 MINIO_ROOT_* 保持一致。
|
||||
MINIO_ROOT_USER=change-minio-user
|
||||
MINIO_ROOT_PASSWORD=change-minio-password
|
||||
STORAGE_ENDPOINT=http://minio:9000
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
package captcha
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"html"
|
||||
"math/big"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrDependencyUnavailable = errors.New("captcha dependency unavailable")
|
||||
ErrInvalid = errors.New("captcha invalid")
|
||||
)
|
||||
|
||||
type Item struct {
|
||||
CaptchaID string `json:"captcha_id"`
|
||||
Image string `json:"image"`
|
||||
ExpiresIn int64 `json:"expires_in"`
|
||||
}
|
||||
|
||||
func Generate(ctx context.Context, redisClient *redis.Client, namespace string, ttl time.Duration) (*Item, error) {
|
||||
if redisClient == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
captchaID, err := randomToken(16)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
code, err := randomCaptchaCode(4)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := redisClient.Set(ctx, key(namespace, captchaID), strings.ToUpper(code), ttl).Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Item{
|
||||
CaptchaID: captchaID,
|
||||
Image: imageDataURL(code),
|
||||
ExpiresIn: int64(ttl.Seconds()),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func Verify(ctx context.Context, redisClient *redis.Client, namespace string, captchaID string, captchaCode string) error {
|
||||
if redisClient == nil {
|
||||
return ErrDependencyUnavailable
|
||||
}
|
||||
captchaID = strings.TrimSpace(captchaID)
|
||||
captchaCode = strings.TrimSpace(captchaCode)
|
||||
if captchaID == "" || captchaCode == "" {
|
||||
return ErrInvalid
|
||||
}
|
||||
|
||||
redisKey := key(namespace, captchaID)
|
||||
stored, err := redisClient.Get(ctx, redisKey).Result()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return ErrInvalid
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_ = redisClient.Del(ctx, redisKey).Err()
|
||||
if strings.ToUpper(captchaCode) != stored {
|
||||
return ErrInvalid
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func key(namespace string, id string) string {
|
||||
namespace = strings.Trim(strings.ToLower(strings.TrimSpace(namespace)), ":")
|
||||
if namespace == "" {
|
||||
namespace = "default"
|
||||
}
|
||||
return "captcha:" + namespace + ":" + id
|
||||
}
|
||||
|
||||
func randomToken(length int) (string, error) {
|
||||
buf := make([]byte, length)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(buf), nil
|
||||
}
|
||||
|
||||
func randomCaptchaCode(length int) (string, error) {
|
||||
const alphabet = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"
|
||||
result := make([]byte, length)
|
||||
for i := range result {
|
||||
n, err := rand.Int(rand.Reader, big.NewInt(int64(len(alphabet))))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
result[i] = alphabet[n.Int64()]
|
||||
}
|
||||
return string(result), nil
|
||||
}
|
||||
|
||||
func imageDataURL(code string) string {
|
||||
safeCode := html.EscapeString(strings.ToUpper(code))
|
||||
svg := fmt.Sprintf(`<svg xmlns="http://www.w3.org/2000/svg" width="132" height="44" viewBox="0 0 132 44">
|
||||
<rect width="132" height="44" rx="8" fill="#eef5f7"/>
|
||||
<path d="M8 32 C32 2, 62 52, 124 12" stroke="#0f766e" stroke-width="2" fill="none" opacity=".28"/>
|
||||
<path d="M10 13 C42 42, 86 0, 122 31" stroke="#2563eb" stroke-width="2" fill="none" opacity=".22"/>
|
||||
<text x="66" y="29" text-anchor="middle" font-family="Menlo,Consolas,monospace" font-size="24" font-weight="700" letter-spacing="4" fill="#111827">%s</text>
|
||||
</svg>`, safeCode)
|
||||
return "data:image/svg+xml;base64," + base64.StdEncoding.EncodeToString([]byte(svg))
|
||||
}
|
||||
@@ -2,16 +2,13 @@ package adminauth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"html"
|
||||
"math/big"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/captcha"
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/modules/auth"
|
||||
|
||||
@@ -38,24 +35,17 @@ func NewRepository(db *gorm.DB, redis *redis.Client, jwt *auth.JWTManager) *Repo
|
||||
}
|
||||
|
||||
func (r *Repository) Captcha(ctx context.Context) (*CaptchaDTO, error) {
|
||||
if r.redis == nil {
|
||||
item, err := captcha.Generate(ctx, r.redis, "admin", captchaTTL)
|
||||
if errors.Is(err, captcha.ErrDependencyUnavailable) {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
captchaID, err := randomToken(16)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
code, err := randomCaptchaCode(4)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := r.redis.Set(ctx, captchaKey(captchaID), strings.ToUpper(code), captchaTTL).Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &CaptchaDTO{
|
||||
CaptchaID: captchaID,
|
||||
Image: captchaImageDataURL(code),
|
||||
ExpiresIn: int64(captchaTTL.Seconds()),
|
||||
CaptchaID: item.CaptchaID,
|
||||
Image: item.Image,
|
||||
ExpiresIn: item.ExpiresIn,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -120,22 +110,14 @@ func (r *Repository) RevokeTokens(ctx context.Context, adminID uint64) error {
|
||||
}
|
||||
|
||||
func (r *Repository) verifyCaptcha(ctx context.Context, captchaID string, captchaCode string) error {
|
||||
if r.redis == nil {
|
||||
err := captcha.Verify(ctx, r.redis, "admin", captchaID, captchaCode)
|
||||
if errors.Is(err, captcha.ErrDependencyUnavailable) {
|
||||
return ErrDependencyUnavailable
|
||||
}
|
||||
key := captchaKey(captchaID)
|
||||
stored, err := r.redis.Get(ctx, key).Result()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
if errors.Is(err, captcha.ErrInvalid) {
|
||||
return ErrCaptchaInvalid
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_ = r.redis.Del(ctx, key).Err()
|
||||
if strings.ToUpper(strings.TrimSpace(captchaCode)) != stored {
|
||||
return ErrCaptchaInvalid
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Repository) FindByID(ctx context.Context, id uint64) (*AdminDTO, error) {
|
||||
@@ -273,39 +255,3 @@ func loginKeyPart(value string) string {
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func captchaKey(id string) string {
|
||||
return "admin:captcha:" + id
|
||||
}
|
||||
|
||||
func randomToken(length int) (string, error) {
|
||||
buf := make([]byte, length)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(buf), nil
|
||||
}
|
||||
|
||||
func randomCaptchaCode(length int) (string, error) {
|
||||
const alphabet = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"
|
||||
result := make([]byte, length)
|
||||
for i := range result {
|
||||
n, err := rand.Int(rand.Reader, big.NewInt(int64(len(alphabet))))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
result[i] = alphabet[n.Int64()]
|
||||
}
|
||||
return string(result), nil
|
||||
}
|
||||
|
||||
func captchaImageDataURL(code string) string {
|
||||
safeCode := html.EscapeString(strings.ToUpper(code))
|
||||
svg := fmt.Sprintf(`<svg xmlns="http://www.w3.org/2000/svg" width="132" height="44" viewBox="0 0 132 44">
|
||||
<rect width="132" height="44" rx="8" fill="#eef5f7"/>
|
||||
<path d="M8 32 C32 2, 62 52, 124 12" stroke="#0f766e" stroke-width="2" fill="none" opacity=".28"/>
|
||||
<path d="M10 13 C42 42, 86 0, 122 31" stroke="#2563eb" stroke-width="2" fill="none" opacity=".22"/>
|
||||
<text x="66" y="29" text-anchor="middle" font-family="Menlo,Consolas,monospace" font-size="24" font-weight="700" letter-spacing="4" fill="#111827">%s</text>
|
||||
</svg>`, safeCode)
|
||||
return "data:image/svg+xml;base64," + base64.StdEncoding.EncodeToString([]byte(svg))
|
||||
}
|
||||
|
||||
@@ -16,6 +16,8 @@ type Handler struct {
|
||||
|
||||
type SendSMSRequest struct {
|
||||
Phone string `json:"phone" binding:"required"`
|
||||
CaptchaID string `json:"captcha_id" binding:"required"`
|
||||
CaptchaCode string `json:"captcha_code" binding:"required"`
|
||||
}
|
||||
|
||||
type LoginRequest struct {
|
||||
@@ -31,6 +33,15 @@ func NewHandler(service *Service) *Handler {
|
||||
return &Handler{service: service}
|
||||
}
|
||||
|
||||
func (h *Handler) Captcha(c *gin.Context) {
|
||||
item, err := h.service.Captcha(c.Request.Context())
|
||||
if err != nil {
|
||||
writeAuthError(c, err)
|
||||
return
|
||||
}
|
||||
response.OK(c, item)
|
||||
}
|
||||
|
||||
// SendSMS 发送短信验证码
|
||||
// @Summary 发送短信验证码
|
||||
// @Description 发送登录验证码到指定手机号
|
||||
@@ -45,10 +56,10 @@ func NewHandler(service *Service) *Handler {
|
||||
func (h *Handler) SendSMS(c *gin.Context) {
|
||||
var req SendSMSRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.BadRequest(c, "手机号不能为空")
|
||||
response.BadRequest(c, "手机号和图形验证码不能为空")
|
||||
return
|
||||
}
|
||||
if err := h.service.SendSMSCode(c.Request.Context(), strings.TrimSpace(req.Phone)); err != nil {
|
||||
if err := h.service.SendSMSCode(c.Request.Context(), strings.TrimSpace(req.Phone), strings.TrimSpace(req.CaptchaID), strings.TrimSpace(req.CaptchaCode)); err != nil {
|
||||
writeAuthError(c, err)
|
||||
return
|
||||
}
|
||||
@@ -125,6 +136,8 @@ func writeAuthError(c *gin.Context, err error) {
|
||||
response.ServiceUnavailable(c, "数据库或 Redis 未连接")
|
||||
case errors.Is(err, ErrInvalidPhone):
|
||||
response.BadRequest(c, "手机号格式不正确")
|
||||
case errors.Is(err, ErrCaptchaInvalid):
|
||||
response.BadRequest(c, "图形验证码错误或已过期")
|
||||
case errors.Is(err, ErrCodeRateLimited):
|
||||
response.Error(c, http.StatusTooManyRequests, "rate_limited", "验证码发送过于频繁")
|
||||
case errors.Is(err, ErrSMSSendFailed):
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"regexp"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/captcha"
|
||||
smsprovider "hfb_sys/backend/internal/integrations/sms"
|
||||
"hfb_sys/backend/internal/model"
|
||||
|
||||
@@ -19,6 +20,7 @@ import (
|
||||
var (
|
||||
ErrDependencyUnavailable = errors.New("dependency unavailable")
|
||||
ErrInvalidPhone = errors.New("invalid phone")
|
||||
ErrCaptchaInvalid = errors.New("captcha invalid")
|
||||
ErrCodeRateLimited = errors.New("sms code rate limited")
|
||||
ErrCodeInvalid = errors.New("sms code invalid")
|
||||
ErrSMSSendFailed = errors.New("sms send failed")
|
||||
@@ -29,6 +31,7 @@ const (
|
||||
smsLoginCooldown = 60 * time.Second
|
||||
smsLoginHourlyLimit = 5
|
||||
smsLoginHourlyWindow = time.Hour
|
||||
smsCaptchaTTL = 3 * time.Minute
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
@@ -48,7 +51,18 @@ func NewService(users *UserRepository, redis *redis.Client, jwt *JWTManager, sms
|
||||
return &Service{users: users, redis: redis, jwt: jwt, sms: sms, log: log}
|
||||
}
|
||||
|
||||
func (s *Service) SendSMSCode(ctx context.Context, phone string) error {
|
||||
func (s *Service) Captcha(ctx context.Context) (*captcha.Item, error) {
|
||||
if s.redis == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
item, err := captcha.Generate(ctx, s.redis, "auth:sms", smsCaptchaTTL)
|
||||
if errors.Is(err, captcha.ErrDependencyUnavailable) {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
return item, err
|
||||
}
|
||||
|
||||
func (s *Service) SendSMSCode(ctx context.Context, phone string, captchaID string, captchaCode string) error {
|
||||
if s.redis == nil {
|
||||
return ErrDependencyUnavailable
|
||||
}
|
||||
@@ -74,6 +88,16 @@ func (s *Service) SendSMSCode(ctx context.Context, phone string) error {
|
||||
return ErrCodeRateLimited
|
||||
}
|
||||
|
||||
if err := captcha.Verify(ctx, s.redis, "auth:sms", captchaID, captchaCode); err != nil {
|
||||
if errors.Is(err, captcha.ErrDependencyUnavailable) {
|
||||
return ErrDependencyUnavailable
|
||||
}
|
||||
if errors.Is(err, captcha.ErrInvalid) {
|
||||
return ErrCaptchaInvalid
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
code, err := randomDigits(6)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -299,6 +299,7 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
|
||||
|
||||
authRoutes := api.Group("/auth")
|
||||
{
|
||||
authRoutes.GET("/captcha", authHandler.Captcha)
|
||||
authRoutes.POST("/sms/send", authHandler.SendSMS)
|
||||
authRoutes.POST("/sms/login", authHandler.Login)
|
||||
authRoutes.POST("/refresh", authHandler.Refresh)
|
||||
|
||||
@@ -47,6 +47,7 @@ STORAGE_SECRET_ACCESS_KEY
|
||||
脚本会自动完成:
|
||||
|
||||
- 检查 `backend/.env` 是否仍指向 `127.0.0.1`、`localhost` 或占位值。
|
||||
- 使用内置 MinIO 时,检查 `STORAGE_ACCESS_KEY_ID` / `STORAGE_SECRET_ACCESS_KEY` 是否和 `MINIO_ROOT_USER` / `MINIO_ROOT_PASSWORD` 一致。
|
||||
- 构建并启动生产容器。
|
||||
- 通过 Caddy 自动申请或续签 HTTPS 证书。
|
||||
- 等待 MySQL、Redis、MinIO 就绪。
|
||||
|
||||
@@ -25,11 +25,24 @@ export interface LoginData {
|
||||
tokens: TokenPair
|
||||
}
|
||||
|
||||
export async function sendSmsCode(phone: string) {
|
||||
export interface AuthCaptcha {
|
||||
captcha_id: string
|
||||
image: string
|
||||
expires_in: number
|
||||
}
|
||||
|
||||
export async function fetchAuthCaptcha() {
|
||||
const { data } = await apiClient.get<ApiResponse<AuthCaptcha>>('/auth/captcha')
|
||||
return data.data
|
||||
}
|
||||
|
||||
export async function sendSmsCode(phone: string, captchaId: string, captchaCode: string) {
|
||||
const { data } = await apiClient.post<ApiResponse<{ phone: string; expires_in: number }>>(
|
||||
'/auth/sms/send',
|
||||
{
|
||||
phone,
|
||||
captcha_id: captchaId,
|
||||
captcha_code: captchaCode,
|
||||
}
|
||||
)
|
||||
return data.data
|
||||
|
||||
@@ -1,20 +1,23 @@
|
||||
<script setup lang="ts">
|
||||
import { readError } from '@/shared/utils/error'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { ChatLineRound, Iphone } from '@element-plus/icons-vue'
|
||||
import { onUnmounted, reactive, ref } from 'vue'
|
||||
import { ChatLineRound, Iphone, Key } from '@element-plus/icons-vue'
|
||||
import { onMounted, onUnmounted, reactive, ref } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
|
||||
import { sendSmsCode } from '@/features/auth/api/auth'
|
||||
import { fetchAuthCaptcha, sendSmsCode, type AuthCaptcha } from '@/features/auth/api/auth'
|
||||
import { useSessionStore } from '@/stores/session'
|
||||
|
||||
const router = useRouter()
|
||||
const session = useSessionStore()
|
||||
const loading = ref(false)
|
||||
const sending = ref(false)
|
||||
const captchaLoading = ref(false)
|
||||
const captcha = ref<AuthCaptcha | null>(null)
|
||||
const countDown = ref(0)
|
||||
const form = reactive({
|
||||
phone: '',
|
||||
captchaCode: '',
|
||||
code: '',
|
||||
})
|
||||
|
||||
@@ -38,23 +41,49 @@ onUnmounted(() => {
|
||||
}
|
||||
})
|
||||
|
||||
onMounted(loadCaptcha)
|
||||
|
||||
async function loadCaptcha() {
|
||||
captchaLoading.value = true
|
||||
try {
|
||||
captcha.value = await fetchAuthCaptcha()
|
||||
form.captchaCode = ''
|
||||
} catch (error) {
|
||||
ElMessage.error(readError(error, '图形验证码加载失败'))
|
||||
} finally {
|
||||
captchaLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSendCode() {
|
||||
if (!form.phone.trim()) {
|
||||
ElMessage.warning('请输入手机号')
|
||||
return
|
||||
}
|
||||
if (!captcha.value?.captcha_id || !form.captchaCode.trim()) {
|
||||
ElMessage.warning('请输入图形验证码')
|
||||
return
|
||||
}
|
||||
sending.value = true
|
||||
try {
|
||||
await sendSmsCode(form.phone)
|
||||
await sendSmsCode(form.phone, captcha.value.captcha_id, form.captchaCode)
|
||||
ElMessage.success('验证码已发送,请注意查收')
|
||||
startCountDown()
|
||||
} catch (error) {
|
||||
ElMessage.error(readError(error, '验证码发送失败'))
|
||||
} finally {
|
||||
await loadCaptcha()
|
||||
sending.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshCaptcha() {
|
||||
if (captchaLoading.value) {
|
||||
return
|
||||
}
|
||||
await loadCaptcha()
|
||||
}
|
||||
|
||||
async function handleLogin() {
|
||||
loading.value = true
|
||||
try {
|
||||
@@ -108,6 +137,29 @@ async function handleLogin() {
|
||||
/>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="图形验证码">
|
||||
<div class="user-captcha-row">
|
||||
<el-input
|
||||
v-model="form.captchaCode"
|
||||
maxlength="4"
|
||||
placeholder="请输入图形验证码"
|
||||
size="large"
|
||||
:prefix-icon="Key"
|
||||
@keyup.enter="handleSendCode"
|
||||
/>
|
||||
<button
|
||||
class="user-captcha-image"
|
||||
type="button"
|
||||
:disabled="captchaLoading"
|
||||
aria-label="刷新图形验证码"
|
||||
@click="refreshCaptcha"
|
||||
>
|
||||
<img v-if="captcha" :src="captcha.image" alt="图形验证码" />
|
||||
<span v-else>刷新</span>
|
||||
</button>
|
||||
</div>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="验证码">
|
||||
<div class="user-code-row">
|
||||
<el-input
|
||||
@@ -311,6 +363,39 @@ async function handleLogin() {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.user-captcha-row {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 132px;
|
||||
gap: 10px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.user-captcha-image {
|
||||
display: grid;
|
||||
height: 46px;
|
||||
place-items: center;
|
||||
overflow: hidden;
|
||||
border: 1px solid #dbe5f0;
|
||||
border-radius: 10px;
|
||||
background: #f8fafc;
|
||||
color: #1477ff;
|
||||
cursor: pointer;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.user-captcha-image:disabled {
|
||||
cursor: wait;
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.user-captcha-image img {
|
||||
display: block;
|
||||
width: 132px;
|
||||
height: 44px;
|
||||
}
|
||||
|
||||
.user-code-row .el-button {
|
||||
height: 46px;
|
||||
border-radius: 10px;
|
||||
|
||||
@@ -1,23 +1,53 @@
|
||||
<script setup lang="ts">
|
||||
import { reactive, ref } from 'vue'
|
||||
import { onMounted, reactive, ref } from 'vue'
|
||||
import { RouterLink, useRoute, useRouter } from 'vue-router'
|
||||
import { showToast, showDialog } from 'vant'
|
||||
|
||||
import { fetchAuthCaptcha, type AuthCaptcha } from '@/features/auth/api/auth'
|
||||
import { useSessionStore } from '@/stores/session'
|
||||
import { useSmsCountdown } from '@/shared/composables/useSmsCountdown'
|
||||
import { readError } from '@/shared/utils/error'
|
||||
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
const session = useSessionStore()
|
||||
const loading = ref(false)
|
||||
const agreed = ref(false)
|
||||
const captchaLoading = ref(false)
|
||||
const captcha = ref<AuthCaptcha | null>(null)
|
||||
const form = reactive({
|
||||
phone: '',
|
||||
captchaCode: '',
|
||||
code: '',
|
||||
})
|
||||
|
||||
const { countDown, sending, handleSendCode } = useSmsCountdown()
|
||||
|
||||
onMounted(loadCaptcha)
|
||||
|
||||
async function loadCaptcha() {
|
||||
captchaLoading.value = true
|
||||
try {
|
||||
captcha.value = await fetchAuthCaptcha()
|
||||
form.captchaCode = ''
|
||||
} catch (error) {
|
||||
showToast({ message: readError(error, '图形验证码加载失败'), icon: 'cross' })
|
||||
} finally {
|
||||
captchaLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function sendCode() {
|
||||
const shouldRefresh = Boolean(form.captchaCode.trim())
|
||||
await handleSendCode(form.phone, {
|
||||
captchaId: captcha.value?.captcha_id || '',
|
||||
captchaCode: form.captchaCode,
|
||||
})
|
||||
if (shouldRefresh) {
|
||||
await loadCaptcha()
|
||||
}
|
||||
}
|
||||
|
||||
async function handleLogin() {
|
||||
if (!agreed.value) {
|
||||
showDialog({
|
||||
@@ -61,6 +91,25 @@ async function handleLogin() {
|
||||
<input v-model="form.phone" type="tel" maxlength="11" placeholder="手机号" />
|
||||
</label>
|
||||
|
||||
<label class="auth-input-row captcha-row">
|
||||
<input
|
||||
v-model="form.captchaCode"
|
||||
type="text"
|
||||
maxlength="4"
|
||||
autocomplete="off"
|
||||
placeholder="图形验证码"
|
||||
/>
|
||||
<button
|
||||
class="captcha-image-button"
|
||||
type="button"
|
||||
:disabled="captchaLoading"
|
||||
@click="loadCaptcha"
|
||||
>
|
||||
<img v-if="captcha" :src="captcha.image" alt="图形验证码" />
|
||||
<span v-else>刷新</span>
|
||||
</button>
|
||||
</label>
|
||||
|
||||
<label class="auth-input-row code-row">
|
||||
<input
|
||||
v-model="form.code"
|
||||
@@ -76,7 +125,7 @@ async function handleLogin() {
|
||||
:disabled="sending || countDown > 0"
|
||||
:loading="sending"
|
||||
class="code-btn"
|
||||
@click="handleSendCode(form.phone)"
|
||||
@click="sendCode"
|
||||
>
|
||||
{{ countDown > 0 ? `${countDown}s` : sending ? '发送中' : '发送验证码' }}
|
||||
</van-button>
|
||||
@@ -212,6 +261,11 @@ async function handleLogin() {
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.auth-input-row.captcha-row {
|
||||
gap: 10px;
|
||||
padding-right: 4px;
|
||||
}
|
||||
|
||||
.auth-input-row input {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
@@ -231,6 +285,33 @@ async function handleLogin() {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.captcha-image-button {
|
||||
display: grid;
|
||||
flex: 0 0 116px;
|
||||
width: 116px;
|
||||
height: 40px;
|
||||
place-items: center;
|
||||
overflow: hidden;
|
||||
border: 1px solid #dbe5f0;
|
||||
border-radius: 8px;
|
||||
background: #f8fafc;
|
||||
color: #1477ff;
|
||||
font-size: 12px;
|
||||
font-weight: 800;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.captcha-image-button:disabled {
|
||||
opacity: 0.65;
|
||||
}
|
||||
|
||||
.captcha-image-button img {
|
||||
display: block;
|
||||
width: 120px;
|
||||
height: 40px;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.code-btn {
|
||||
min-width: 82px;
|
||||
height: 32px;
|
||||
|
||||
@@ -1,24 +1,54 @@
|
||||
<script setup lang="ts">
|
||||
import { reactive, ref } from 'vue'
|
||||
import { onMounted, reactive, ref } from 'vue'
|
||||
import { RouterLink, useRoute, useRouter } from 'vue-router'
|
||||
import { showToast } from 'vant'
|
||||
|
||||
import { fetchAuthCaptcha, type AuthCaptcha } from '@/features/auth/api/auth'
|
||||
import { useSessionStore } from '@/stores/session'
|
||||
import { useSmsCountdown } from '@/shared/composables/useSmsCountdown'
|
||||
import { readError } from '@/shared/utils/error'
|
||||
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
const session = useSessionStore()
|
||||
const loading = ref(false)
|
||||
const agreed = ref(false)
|
||||
const captchaLoading = ref(false)
|
||||
const captcha = ref<AuthCaptcha | null>(null)
|
||||
const form = reactive({
|
||||
phone: '',
|
||||
captchaCode: '',
|
||||
code: '',
|
||||
inviteCode: '',
|
||||
})
|
||||
|
||||
const { countDown, sending, handleSendCode } = useSmsCountdown()
|
||||
|
||||
onMounted(loadCaptcha)
|
||||
|
||||
async function loadCaptcha() {
|
||||
captchaLoading.value = true
|
||||
try {
|
||||
captcha.value = await fetchAuthCaptcha()
|
||||
form.captchaCode = ''
|
||||
} catch (error) {
|
||||
showToast({ message: readError(error, '图形验证码加载失败'), icon: 'cross' })
|
||||
} finally {
|
||||
captchaLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function sendCode() {
|
||||
const shouldRefresh = Boolean(form.captchaCode.trim())
|
||||
await handleSendCode(form.phone, {
|
||||
captchaId: captcha.value?.captcha_id || '',
|
||||
captchaCode: form.captchaCode,
|
||||
})
|
||||
if (shouldRefresh) {
|
||||
await loadCaptcha()
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRegister() {
|
||||
if (!agreed.value) {
|
||||
showToast({
|
||||
@@ -68,6 +98,25 @@ async function handleRegister() {
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label class="auth-input-row captcha-row">
|
||||
<input
|
||||
v-model="form.captchaCode"
|
||||
type="text"
|
||||
maxlength="4"
|
||||
autocomplete="off"
|
||||
placeholder="图形验证码"
|
||||
/>
|
||||
<button
|
||||
class="captcha-image-button"
|
||||
type="button"
|
||||
:disabled="captchaLoading"
|
||||
@click="loadCaptcha"
|
||||
>
|
||||
<img v-if="captcha" :src="captcha.image" alt="图形验证码" />
|
||||
<span v-else>刷新</span>
|
||||
</button>
|
||||
</label>
|
||||
|
||||
<label class="auth-input-row code-row">
|
||||
<input
|
||||
v-model="form.code"
|
||||
@@ -83,7 +132,7 @@ async function handleRegister() {
|
||||
:disabled="sending || countDown > 0"
|
||||
:loading="sending"
|
||||
class="code-btn"
|
||||
@click="handleSendCode(form.phone)"
|
||||
@click="sendCode"
|
||||
>
|
||||
{{ countDown > 0 ? `${countDown}s` : sending ? '发送中' : '发送验证码' }}
|
||||
</van-button>
|
||||
@@ -223,6 +272,11 @@ async function handleRegister() {
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.auth-input-row.captcha-row {
|
||||
gap: 10px;
|
||||
padding-right: 4px;
|
||||
}
|
||||
|
||||
.auth-input-row input {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
@@ -242,6 +296,33 @@ async function handleRegister() {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.captcha-image-button {
|
||||
display: grid;
|
||||
flex: 0 0 116px;
|
||||
width: 116px;
|
||||
height: 40px;
|
||||
place-items: center;
|
||||
overflow: hidden;
|
||||
border: 1px solid #dbe5f0;
|
||||
border-radius: 8px;
|
||||
background: #f8fafc;
|
||||
color: #1477ff;
|
||||
font-size: 12px;
|
||||
font-weight: 800;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.captcha-image-button:disabled {
|
||||
opacity: 0.65;
|
||||
}
|
||||
|
||||
.captcha-image-button img {
|
||||
display: block;
|
||||
width: 120px;
|
||||
height: 40px;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.code-btn {
|
||||
min-width: 82px;
|
||||
height: 32px;
|
||||
|
||||
@@ -26,15 +26,22 @@ export function useSmsCountdown() {
|
||||
}
|
||||
})
|
||||
|
||||
async function handleSendCode(phone: string) {
|
||||
async function handleSendCode(
|
||||
phone: string,
|
||||
captcha?: { captchaId: string; captchaCode: string }
|
||||
) {
|
||||
if (!phone.trim()) {
|
||||
showToast({ message: '请输入手机号', icon: 'warning-o' })
|
||||
return false
|
||||
}
|
||||
if (!captcha?.captchaId || !captcha.captchaCode.trim()) {
|
||||
showToast({ message: '请输入图形验证码', icon: 'warning-o' })
|
||||
return false
|
||||
}
|
||||
|
||||
sending.value = true
|
||||
try {
|
||||
await sendSmsCode(phone)
|
||||
await sendSmsCode(phone, captcha.captchaId, captcha.captchaCode)
|
||||
showToast({
|
||||
message: '验证码已发送,请注意查收',
|
||||
icon: 'passed',
|
||||
|
||||
+11
-4
@@ -128,6 +128,7 @@ validate_env() {
|
||||
fi
|
||||
|
||||
local app_env caddy_domain caddy_email mysql_dsn redis_addr storage_endpoint
|
||||
local minio_root_user minio_root_password storage_access_key_id storage_secret_access_key
|
||||
app_env="$(require_env APP_ENV)"
|
||||
caddy_domain="$(require_env CADDY_DOMAIN)"
|
||||
caddy_email="$(require_env CADDY_EMAIL)"
|
||||
@@ -139,10 +140,10 @@ validate_env() {
|
||||
require_env MYSQL_USER >/dev/null
|
||||
require_env MYSQL_PASSWORD >/dev/null
|
||||
require_env JWT_SECRET >/dev/null
|
||||
require_env MINIO_ROOT_USER >/dev/null
|
||||
require_env MINIO_ROOT_PASSWORD >/dev/null
|
||||
require_env STORAGE_ACCESS_KEY_ID >/dev/null
|
||||
require_env STORAGE_SECRET_ACCESS_KEY >/dev/null
|
||||
minio_root_user="$(require_env MINIO_ROOT_USER)"
|
||||
minio_root_password="$(require_env MINIO_ROOT_PASSWORD)"
|
||||
storage_access_key_id="$(require_env STORAGE_ACCESS_KEY_ID)"
|
||||
storage_secret_access_key="$(require_env STORAGE_SECRET_ACCESS_KEY)"
|
||||
|
||||
if [[ "${app_env}" != "production" ]]; then
|
||||
log_warn "APP_ENV 当前是 ${app_env},生产部署建议改为 production"
|
||||
@@ -173,6 +174,12 @@ validate_env() {
|
||||
log_error "STORAGE_ENDPOINT 仍指向本机,请改为 http://minio:9000"
|
||||
exit 1
|
||||
fi
|
||||
if [[ "${storage_endpoint}" == "http://minio:9000" || "${storage_endpoint}" == "minio:9000" ]]; then
|
||||
if [[ "${storage_access_key_id}" != "${minio_root_user}" || "${storage_secret_access_key}" != "${minio_root_password}" ]]; then
|
||||
log_error "使用内置 MinIO 时,STORAGE_ACCESS_KEY_ID/SECRET_ACCESS_KEY 必须和 MINIO_ROOT_USER/ROOT_PASSWORD 保持一致"
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
if awk -F= '/^[A-Z0-9_]+=/{ if ($0 ~ /=(change-|保持你的|你的)/) found=1 } END { exit found ? 0 : 1 }' "${BACKEND_ENV}"; then
|
||||
log_error "backend/.env 里还有占位值,请先替换后再部署"
|
||||
exit 1
|
||||
|
||||
Reference in New Issue
Block a user