feat: rebuild pet app and backend around core care flows

This commit is contained in:
2026-10-01 13:11:30 +08:00
parent 51ead8f411
commit bfcf8788a4
321 changed files with 4918 additions and 25199 deletions
+174
View File
@@ -0,0 +1,174 @@
package httpapi
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"time"
"github.com/gin-gonic/gin"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
"github.com/sundynix/pets-be/internal/model"
)
func (a *API) SeedAdmin() error {
if a.cfg.Admin.Password == "" {
if a.cfg.Server.Mode == "release" {
return errors.New("admin password is required in release mode")
}
return nil
}
var admin model.Admin
err := a.db.Where("username = ?", a.cfg.Admin.Username).First(&admin).Error
missing := errors.Is(err, gorm.ErrRecordNotFound)
if err != nil && !missing {
return err
}
if !missing && bcrypt.CompareHashAndPassword([]byte(admin.PasswordHash), []byte(a.cfg.Admin.Password)) == nil {
return nil
}
hash, err := bcrypt.GenerateFromPassword([]byte(a.cfg.Admin.Password), bcrypt.DefaultCost)
if err != nil {
return err
}
if missing {
return a.db.Create(&model.Admin{Username: a.cfg.Admin.Username, PasswordHash: string(hash)}).Error
}
return a.db.Model(&admin).Update("password_hash", string(hash)).Error
}
func (a *API) adminLogin(c *gin.Context) {
var in struct {
Username string `json:"username" binding:"required"`
Password string `json:"password" binding:"required"`
}
if err := c.ShouldBindJSON(&in); err != nil {
fail(c, http.StatusBadRequest, "请输入用户名和密码")
return
}
var admin model.Admin
if err := a.db.Where("username = ?", in.Username).First(&admin).Error; err != nil || bcrypt.CompareHashAndPassword([]byte(admin.PasswordHash), []byte(in.Password)) != nil {
fail(c, http.StatusUnauthorized, "用户名或密码错误")
return
}
token, err := a.token(admin.ID, "admin")
if err != nil {
fail(c, http.StatusInternalServerError, "签发令牌失败")
return
}
ok(c, gin.H{"token": token, "admin": gin.H{"id": admin.ID, "username": admin.Username}})
}
func (a *API) devLogin(c *gin.Context) {
if !a.cfg.Auth.DevLogin || a.cfg.Server.Mode == "release" {
fail(c, http.StatusNotFound, "接口不存在")
return
}
var in struct {
Key string `json:"key" binding:"required"`
Nickname string `json:"nickname"`
}
if err := c.ShouldBindJSON(&in); err != nil || len(in.Key) > 64 {
fail(c, http.StatusBadRequest, "开发登录参数无效")
return
}
name := strings.TrimSpace(in.Nickname)
if name == "" {
name = "柯基家长"
}
user, err := a.findOrCreateUser("dev:"+in.Key, name)
if err != nil {
fail(c, http.StatusInternalServerError, "登录失败")
return
}
a.loginUser(c, user)
}
func (a *API) login(c *gin.Context) {
var in struct {
Code string `json:"code" binding:"required"`
}
if err := c.ShouldBindJSON(&in); err != nil || a.cfg.WeChat.AppID == "" || a.cfg.WeChat.AppSecret == "" {
fail(c, http.StatusBadRequest, "微信登录配置或参数无效")
return
}
ctx, cancel := context.WithTimeout(c.Request.Context(), 6*time.Second)
defer cancel()
endpoint := "https://api.weixin.qq.com/sns/jscode2session?" + url.Values{
"appid": {a.cfg.WeChat.AppID}, "secret": {a.cfg.WeChat.AppSecret},
"js_code": {in.Code}, "grant_type": {"authorization_code"},
}.Encode()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
fail(c, http.StatusInternalServerError, "微信登录失败")
return
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
fail(c, http.StatusBadGateway, "微信登录暂不可用")
return
}
defer resp.Body.Close()
var wx struct {
OpenID string `json:"openid"`
ErrCode int `json:"errcode"`
}
if resp.StatusCode != http.StatusOK || json.NewDecoder(resp.Body).Decode(&wx) != nil || wx.ErrCode != 0 || wx.OpenID == "" {
fail(c, http.StatusUnauthorized, "微信登录凭证无效")
return
}
user, err := a.findOrCreateUser(wx.OpenID, "柯基家长")
if err != nil {
fail(c, http.StatusInternalServerError, "登录失败")
return
}
a.loginUser(c, user)
}
func (a *API) findOrCreateUser(openID, nickname string) (model.User, error) {
var user model.User
err := a.db.Where("open_id = ?", openID).First(&user).Error
if err == nil {
return user, nil
}
if !errors.Is(err, gorm.ErrRecordNotFound) {
return user, err
}
user = model.User{OpenID: openID, Nickname: nickname}
if err := a.db.Create(&user).Error; err != nil {
// A concurrent login may have inserted the same open_id.
if lookup := a.db.Where("open_id = ?", openID).First(&user).Error; lookup == nil {
return user, nil
}
return user, fmt.Errorf("create user: %w", err)
}
return user, nil
}
func (a *API) loginUser(c *gin.Context, user model.User) {
if user.Disabled {
fail(c, http.StatusForbidden, "账号已停用")
return
}
token, err := a.token(user.ID, "user")
if err != nil {
fail(c, http.StatusInternalServerError, "签发令牌失败")
return
}
ok(c, gin.H{"token": token, "user": a.userView(user)})
}
func (a *API) me(c *gin.Context) {
var user model.User
if err := a.db.First(&user, "id = ?", actor(c)).Error; err != nil {
fail(c, http.StatusNotFound, "用户不存在")
return
}
ok(c, a.userView(user))
}