Files
mengpost/mengpost-backend/handlers/account.go

66 lines
1.6 KiB
Go

package handlers
import (
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"mengpost-backend/models"
)
func ListAccounts(c *gin.Context) {
list, err := models.ListAccounts()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, list)
}
func CreateAccount(c *gin.Context) {
var a models.Account
if err := c.ShouldBindJSON(&a); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if a.Email == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "email 必填"})
return
}
if a.AuthType != models.AuthTypeOAuthMicrosoft && a.Password == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "普通账户需要填写 password"})
return
}
if err := models.CreateAccount(&a); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
a.Password = ""
c.JSON(http.StatusOK, a)
}
func UpdateAccount(c *gin.Context) {
id, _ := strconv.ParseInt(c.Param("id"), 10, 64)
var a models.Account
if err := c.ShouldBindJSON(&a); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
a.ID = id
if err := models.UpdateAccount(&a); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"ok": true})
}
func DeleteAccount(c *gin.Context) {
id, _ := strconv.ParseInt(c.Param("id"), 10, 64)
if err := models.DeleteAccount(id); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"ok": true})
}