This commit is contained in:
“xHuPo” 2025-05-22 12:06:34 +08:00
parent 53e59ddf89
commit 079542e431
9 changed files with 191 additions and 57 deletions

View file

@ -2,6 +2,7 @@ package handlers
import (
"encoding/json"
"log"
"net/http"
)
@ -19,43 +20,53 @@ type OTP struct {
func (h *Handler) UpdateOrCreateOtp(w http.ResponseWriter, r *http.Request) {
var req OtpRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid request payload", http.StatusBadRequest)
WriteError(w, "Failed to parse request body", http.StatusBadRequest)
return
}
num := len(*req.Token)
if req.OpenID == "" {
WriteError(w, "OpenID is required", http.StatusBadRequest)
return
}
if req.Token == nil || len(*req.Token) == 0 {
WriteError(w, "Token is required", http.StatusBadRequest)
return
}
log.Printf("Saving OTP for user: %s token count:: %d", req.OpenID, len(*req.Token))
// 插入或更新 OTP 记录
query := `
INSERT INTO otp (openid, num, token)
VALUES ($1, $2, $3)
ON CONFLICT (openid) DO UPDATE SET num = EXCLUDED.num, token = EXCLUDED.token
}
`
_, err := h.DB.Exec(query, req.OpenID, req.Token, num)
_, err := h.DB.Exec(query, req.OpenID, len(*req.Token), req.Token)
if err != nil {
http.Error(w, "Failed to update or create OTP", http.StatusInternalServerError)
WriteError(w, "Failed to update or create OTP", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("OTP updated or created successfully"))
WriteJSON(w, Response{Code: 0, Message: "Success"}, http.StatusOK)
}
func (h *Handler) GetOtp(w http.ResponseWriter, r *http.Request) {
openid := r.URL.Query().Get("openid")
if openid == "" {
http.Error(w, "未登录", http.StatusBadRequest)
WriteError(w, "OpenID is required", http.StatusBadRequest)
return
}
var otp OtpRequest
err := h.DB.Get(&otp, "SELECT token, num, openid FROM otp WHERE openid=$1", openid)
err := h.DB.Get(&otp, "SELECT openid, token, num FROM otp WHERE openid=$1", openid)
if err != nil {
http.Error(w, "OTP not found", http.StatusNotFound)
WriteError(w, "Failed to get OTP", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(otp)
WriteJSON(w, Response{Code: 0, Message: "Success", Data: otp}, http.StatusOK)
}