feat(server): web 用户中心后端(1/3) — GetMe 补字段 + logout + redeem 路径别名 + 用户表 totp/sub_token
为 web 用户中心接通真后端做准备(保持 snake_case 不破 app): - migration 000013:users 加 sub_token / totp_secret_enc / totp_enabled。 - GetMe 扩展:补 devices_used/devices_max/quota_today_min/data_today_gb/ weekly_gb/totp_enabled/expires_at(聚合 plans+usage_daily+devices+totp 列), 保留原 expire_at 等字段不破 app。 - POST /v1/auth/logout:X-Refresh-Token 头 → RevokeRefresh,幂等 204。 - /v1/me/redeem 别名(web 用),保留 /v1/redeem(app 用)。 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
@@ -21,29 +22,43 @@ func NewAccountAPI(db *sql.DB) *AccountAPI { return &AccountAPI{db: db} }
|
||||
// ─── GET /v1/me ──────────────────────────────────────────────────────────────
|
||||
|
||||
type meResponse struct {
|
||||
UUID string `json:"uuid"`
|
||||
Email string `json:"email"`
|
||||
DpUUID string `json:"dp_uuid"`
|
||||
Plan string `json:"plan"` // "free" | "pro" | "team"
|
||||
ExpireAt *string `json:"expire_at"` // RFC3339 UTC, null = no active sub
|
||||
UUID string `json:"uuid"`
|
||||
Email string `json:"email"`
|
||||
DpUUID string `json:"dp_uuid"`
|
||||
Plan string `json:"plan"` // "free" | "pro" | "team"
|
||||
// expire_at kept for the existing app; expires_at is the same value for the
|
||||
// web user-center (both RFC3339 UTC, null = no active sub).
|
||||
ExpireAt *string `json:"expire_at"`
|
||||
ExpiresAt *string `json:"expires_at"`
|
||||
// Web user-center fields.
|
||||
DevicesUsed int `json:"devices_used"`
|
||||
DevicesMax int `json:"devices_max"`
|
||||
QuotaTodayMin *int `json:"quota_today_min"` // null = unlimited (pro/team)
|
||||
DataTodayGB float64 `json:"data_today_gb"`
|
||||
WeeklyGB []float64 `json:"weekly_gb"` // last 7 days, oldest→newest
|
||||
TOTPEnabled bool `json:"totp_enabled"`
|
||||
}
|
||||
|
||||
const bytesPerGB = 1024.0 * 1024.0 * 1024.0
|
||||
|
||||
// GetMe handles GET /v1/me.
|
||||
func (a *AccountAPI) GetMe(w http.ResponseWriter, r *http.Request) {
|
||||
uid, ok := auth.UserIDFromContext(r.Context())
|
||||
ctx := r.Context()
|
||||
uid, ok := auth.UserIDFromContext(ctx)
|
||||
if !ok {
|
||||
apierr.WriteJSON(w, http.StatusUnauthorized, apierr.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
var (
|
||||
uuid string
|
||||
email string
|
||||
dpUUID string
|
||||
uuid string
|
||||
email string
|
||||
dpUUID string
|
||||
totpEnabled bool
|
||||
)
|
||||
if err := a.db.QueryRowContext(r.Context(),
|
||||
`SELECT uuid, email, dp_uuid FROM users WHERE id = ? AND status = 'active'`, uid,
|
||||
).Scan(&uuid, &email, &dpUUID); err == sql.ErrNoRows {
|
||||
if err := a.db.QueryRowContext(ctx,
|
||||
`SELECT uuid, email, dp_uuid, totp_enabled FROM users WHERE id = ? AND status = 'active'`, uid,
|
||||
).Scan(&uuid, &email, &dpUUID, &totpEnabled); err == sql.ErrNoRows {
|
||||
apierr.WriteJSON(w, http.StatusNotFound, apierr.ErrNotFound)
|
||||
return
|
||||
} else if err != nil {
|
||||
@@ -51,39 +66,105 @@ func (a *AccountAPI) GetMe(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
// Best active subscription.
|
||||
var planCode string
|
||||
var expiresAt sql.NullTime
|
||||
err := a.db.QueryRowContext(r.Context(), `
|
||||
SELECT p.code, s.expires_at
|
||||
// Best active subscription → plan code + limits + expiry. Falls back to free.
|
||||
var (
|
||||
planCode string
|
||||
maxDevices int
|
||||
dailyMinutes sql.NullInt64
|
||||
expiresAt sql.NullTime
|
||||
)
|
||||
err := a.db.QueryRowContext(ctx, `
|
||||
SELECT p.code, p.max_devices, p.daily_minutes, s.expires_at
|
||||
FROM subscriptions s
|
||||
JOIN plans p ON p.id = s.plan_id
|
||||
WHERE s.user_id = ? AND s.expires_at > UTC_TIMESTAMP()
|
||||
ORDER BY s.expires_at DESC
|
||||
LIMIT 1
|
||||
`, uid).Scan(&planCode, &expiresAt)
|
||||
`, uid).Scan(&planCode, &maxDevices, &dailyMinutes, &expiresAt)
|
||||
if err == sql.ErrNoRows {
|
||||
planCode = "free"
|
||||
if err := a.db.QueryRowContext(ctx,
|
||||
`SELECT max_devices, daily_minutes FROM plans WHERE code = 'free'`,
|
||||
).Scan(&maxDevices, &dailyMinutes); err != nil && err != sql.ErrNoRows {
|
||||
apierr.WriteJSON(w, http.StatusInternalServerError, apierr.ErrInternal)
|
||||
return
|
||||
}
|
||||
} else if err != nil {
|
||||
apierr.WriteJSON(w, http.StatusInternalServerError, apierr.ErrInternal)
|
||||
return
|
||||
}
|
||||
|
||||
var devicesUsed int
|
||||
_ = a.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM devices WHERE user_id = ?`, uid).Scan(&devicesUsed)
|
||||
|
||||
// Today's usage (UTC). Missing row → zero.
|
||||
var todayBytes uint64
|
||||
var todayMinutes int
|
||||
_ = a.db.QueryRowContext(ctx, `
|
||||
SELECT COALESCE(bytes_up, 0) + COALESCE(bytes_down, 0), COALESCE(minutes_used, 0)
|
||||
FROM usage_daily WHERE user_id = ? AND date = UTC_DATE()
|
||||
`, uid).Scan(&todayBytes, &todayMinutes)
|
||||
|
||||
resp := meResponse{
|
||||
UUID: uuid,
|
||||
Email: email,
|
||||
DpUUID: dpUUID,
|
||||
Plan: planCode,
|
||||
UUID: uuid,
|
||||
Email: email,
|
||||
DpUUID: dpUUID,
|
||||
Plan: planCode,
|
||||
DevicesUsed: devicesUsed,
|
||||
DevicesMax: maxDevices,
|
||||
DataTodayGB: float64(todayBytes) / bytesPerGB,
|
||||
WeeklyGB: a.weeklyGB(ctx, uid),
|
||||
TOTPEnabled: totpEnabled,
|
||||
}
|
||||
if expiresAt.Valid {
|
||||
s := expiresAt.Time.UTC().Format(time.RFC3339)
|
||||
resp.ExpireAt = &s
|
||||
resp.ExpiresAt = &s
|
||||
}
|
||||
// quota_today_min: null when the plan is unlimited, else remaining minutes.
|
||||
if dailyMinutes.Valid {
|
||||
rem := int(dailyMinutes.Int64) - todayMinutes
|
||||
if rem < 0 {
|
||||
rem = 0
|
||||
}
|
||||
resp.QuotaTodayMin = &rem
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
_ = json.NewEncoder(w).Encode(resp)
|
||||
}
|
||||
|
||||
// weeklyGB returns total GB per day for the last 7 UTC days (oldest→newest),
|
||||
// filling days with no usage row as 0.
|
||||
func (a *AccountAPI) weeklyGB(ctx context.Context, uid int64) []float64 {
|
||||
out := make([]float64, 7)
|
||||
rows, err := a.db.QueryContext(ctx, `
|
||||
SELECT date, COALESCE(bytes_up, 0) + COALESCE(bytes_down, 0)
|
||||
FROM usage_daily
|
||||
WHERE user_id = ? AND date >= UTC_DATE() - INTERVAL 6 DAY
|
||||
`, uid)
|
||||
if err != nil {
|
||||
return out
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
byDay := make(map[string]uint64, 7)
|
||||
for rows.Next() {
|
||||
var d time.Time
|
||||
var b uint64
|
||||
if err := rows.Scan(&d, &b); err != nil {
|
||||
return out
|
||||
}
|
||||
byDay[d.UTC().Format("2006-01-02")] = b
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
for i := 0; i < 7; i++ {
|
||||
day := now.AddDate(0, 0, -(6 - i)).Format("2006-01-02")
|
||||
out[i] = float64(byDay[day]) / bytesPerGB
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ─── GET /v1/plans ───────────────────────────────────────────────────────────
|
||||
|
||||
type planResponse struct {
|
||||
|
||||
Reference in New Issue
Block a user