otpm/handlers/otp.go
“xHuPo” 25c5f530b8 alpha
2025-05-22 16:07:55 +08:00

71 lines
1.7 KiB
Go

package handlers
import (
"encoding/json"
"log"
"net/http"
)
type OtpRequest struct {
OpenID string `json:"openid"`
Num int `json:"num"`
Token *[]OTP `json:"token"`
}
type OTP struct {
Issuer string `json:"issuer"`
Remark string `json:"remark"`
Secret string `json:"secret"`
}
func (h *Handler) UpdateOrCreateOtp(w http.ResponseWriter, r *http.Request) {
var req OtpRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
WriteError(w, "Failed to parse request body", http.StatusBadRequest)
return
}
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, token)
VALUES ($1, $2)
ON CONFLICT (openid) DO UPDATE SET token = EXCLUDED.token
`
_, err := h.DB.Exec(query, req.OpenID, req.Token)
if err != nil {
WriteError(w, "Failed to update or create OTP", http.StatusInternalServerError)
return
}
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 == "" {
WriteError(w, "OpenID is required", http.StatusBadRequest)
return
}
var otp OtpRequest
err := h.DB.Get(&otp, "SELECT openid, token FROM otp WHERE openid=$1", openid)
if err != nil {
WriteError(w, "Failed to get OTP", http.StatusInternalServerError)
return
}
WriteJSON(w, Response{Code: 0, Message: "Success", Data: otp}, http.StatusOK)
}