568 lines
15 KiB
Go
568 lines
15 KiB
Go
package handler
|
|
|
|
import (
|
|
"errors"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"opencatd-open/internal/utils"
|
|
"opencatd-open/team/consts"
|
|
dto "opencatd-open/team/dto/team"
|
|
"opencatd-open/team/model"
|
|
"opencatd-open/team/service"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/google/uuid"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type TeamHandler struct {
|
|
db *gorm.DB
|
|
userService service.UserService
|
|
tokenService service.TokenService
|
|
keyService service.ApiKeyService
|
|
usageService service.UsageService
|
|
}
|
|
|
|
func NewTeamHandler(userService service.UserService, tokenService service.TokenService, keyService service.ApiKeyService, usageService service.UsageService) *TeamHandler {
|
|
return &TeamHandler{
|
|
userService: userService,
|
|
tokenService: tokenService,
|
|
keyService: keyService,
|
|
usageService: usageService,
|
|
}
|
|
}
|
|
|
|
// initadmin
|
|
func (h *TeamHandler) InitAdmin(c *gin.Context) {
|
|
admin, err := h.userService.GetUser(c, 1)
|
|
|
|
if err != nil {
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
user := &model.User{
|
|
Name: "root",
|
|
Username: "root",
|
|
Password: "openteam",
|
|
Role: int(consts.RoleSuperAdmin),
|
|
Tokens: []model.Token{
|
|
{
|
|
Name: "default",
|
|
Key: "team-" + strings.ReplaceAll(uuid.New().String(), "-", ""),
|
|
UnlimitedQuota: true,
|
|
},
|
|
},
|
|
}
|
|
if err := h.userService.CreateUser(c, user); err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
var result = dto.UserInfo{
|
|
ID: int(user.ID),
|
|
Name: user.Name,
|
|
Token: user.Tokens[0].Key,
|
|
Status: utils.ToPtr(user.Status == consts.StatusEnabled),
|
|
}
|
|
|
|
c.JSON(http.StatusOK, result)
|
|
return
|
|
} else {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
}
|
|
if admin != nil {
|
|
c.JSON(http.StatusForbidden, gin.H{
|
|
"error": "super user already exists, use cli to reset password",
|
|
})
|
|
return
|
|
}
|
|
}
|
|
|
|
func (h *TeamHandler) Me(c *gin.Context) {
|
|
// token := c.GetHeader("Authorization")
|
|
// token = strings.TrimPrefix(token, "Bearer ")
|
|
// userToken, err := h.tokenService.GetTokenByKey(token)
|
|
// if err != nil {
|
|
// c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
|
|
// return
|
|
// }
|
|
// if userToken.ID != 1 {
|
|
// c.JSON(http.StatusForbidden, gin.H{"error": "only first user token can access"})
|
|
// return
|
|
// }
|
|
token, exists := c.Get("token")
|
|
if !exists {
|
|
c.JSON(http.StatusNotFound, gin.H{"error": "token not found"})
|
|
return
|
|
}
|
|
userToken := token.(*model.Token)
|
|
|
|
c.JSON(http.StatusOK, dto.UserInfo{
|
|
ID: int(userToken.UserID),
|
|
Name: userToken.User.Name,
|
|
Token: userToken.Key,
|
|
Status: utils.ToPtr(userToken.User.Status == consts.StatusEnabled),
|
|
})
|
|
|
|
}
|
|
|
|
// CreateUser 创建用户
|
|
func (h *TeamHandler) CreateUser(c *gin.Context) {
|
|
var userReq dto.UserInfo
|
|
if err := c.ShouldBindJSON(&userReq); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid input"})
|
|
return
|
|
}
|
|
|
|
token, exists := c.Get("token")
|
|
if !exists {
|
|
c.JSON(http.StatusNotFound, gin.H{"error": "Unauthorized"})
|
|
return
|
|
}
|
|
userToken := token.(*model.Token)
|
|
if userToken.User.Role < int(consts.RoleAdmin) {
|
|
create := &model.Token{
|
|
Name: userReq.Name,
|
|
Key: "team-" + strings.ReplaceAll(uuid.New().String(), "-", ""),
|
|
}
|
|
if err := h.tokenService.Create(c.Request.Context(), create); err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
} else {
|
|
user := &model.User{
|
|
Name: userReq.Name,
|
|
Username: userReq.Name,
|
|
Role: int(consts.RoleUser),
|
|
Tokens: []model.Token{
|
|
{
|
|
Name: "default",
|
|
Key: "team-" + strings.ReplaceAll(uuid.New().String(), "-", ""),
|
|
},
|
|
},
|
|
}
|
|
|
|
// 默认角色为普通用户
|
|
if err := h.userService.CreateUser(c.Request.Context(), user); err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{"message": "ok"})
|
|
}
|
|
|
|
// GetUser 获取用户信息
|
|
func (h *TeamHandler) GetUser(c *gin.Context) {
|
|
idStr := c.Param("id")
|
|
id, err := strconv.ParseInt(idStr, 10, 64)
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid user id"})
|
|
return
|
|
}
|
|
|
|
user, err := h.userService.GetUser(c.Request.Context(), id)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, user)
|
|
}
|
|
|
|
// UpdateUser 更新用户信息
|
|
func (h *TeamHandler) UpdateUser(c *gin.Context) {
|
|
var user model.User
|
|
if err := c.ShouldBindJSON(&user); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid input"})
|
|
return
|
|
}
|
|
token, exists := c.Get("token")
|
|
if !exists {
|
|
c.JSON(http.StatusNotFound, gin.H{"error": "Unauthorized"})
|
|
return
|
|
}
|
|
userToken := token.(*model.Token)
|
|
|
|
operatorID := userToken.UserID // 假设从上下文中获取操作者ID
|
|
if err := h.userService.UpdateUser(c.Request.Context(), &user, operatorID); err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{"message": "ok"})
|
|
}
|
|
|
|
// DeleteUser 删除用户
|
|
func (h *TeamHandler) DeleteUser(c *gin.Context) {
|
|
idStr := c.Param("id")
|
|
id, err := strconv.ParseInt(idStr, 10, 64)
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid user id"})
|
|
return
|
|
}
|
|
|
|
token, exists := c.Get("token")
|
|
if !exists {
|
|
c.JSON(http.StatusNotFound, gin.H{"error": "Unauthorized"})
|
|
return
|
|
}
|
|
userToken := token.(*model.Token)
|
|
|
|
if userToken.User.Role < int(consts.RoleAdmin) { // 用户只能删除自己的token
|
|
err := h.tokenService.Delete(c.Request.Context(), int(id))
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
} else {
|
|
if err := h.userService.DeleteUser(c.Request.Context(), id, userToken.UserID); err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{"message": "ok"})
|
|
}
|
|
|
|
func (h *TeamHandler) ListUsages(c *gin.Context) {
|
|
fromStr := c.Query("from")
|
|
toStr := c.Query("to")
|
|
|
|
var from, to time.Time
|
|
loc, _ := time.LoadLocation("Local")
|
|
|
|
var listUsage []*dto.UsageInfo
|
|
var err error
|
|
|
|
if fromStr != "" && toStr != "" {
|
|
|
|
from, err = time.Parse("2006-01-02", fromStr)
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid from date"})
|
|
return
|
|
}
|
|
to, err = time.Parse("2006-01-02", toStr)
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid to date"})
|
|
return
|
|
}
|
|
} else {
|
|
year, month, _ := time.Now().In(loc).Date()
|
|
from = time.Date(year, month, 1, 0, 0, 0, 0, loc)
|
|
to = from.AddDate(0, 1, 0)
|
|
}
|
|
|
|
token, _ := c.Get("token")
|
|
userToken := token.(*model.Token)
|
|
if userToken.User.Role < int(consts.RoleAdmin) {
|
|
listUsage, err = h.usageService.ListByDateRange(c.Request.Context(), from, to, map[string]interface{}{"user_id": userToken.UserID})
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
} else {
|
|
listUsage, err = h.usageService.ListByDateRange(c.Request.Context(), from, to, nil)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
}
|
|
|
|
c.JSON(http.StatusOK, listUsage)
|
|
|
|
}
|
|
|
|
// ListUsers 获取用户列表
|
|
func (h *TeamHandler) ListUsers(c *gin.Context) {
|
|
pageStr := c.DefaultQuery("page", "1")
|
|
pageSizeStr := c.DefaultQuery("pageSize", "100")
|
|
|
|
page, err := strconv.Atoi(pageStr)
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid page number"})
|
|
return
|
|
}
|
|
|
|
pageSize, err := strconv.Atoi(pageSizeStr)
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid page size"})
|
|
return
|
|
}
|
|
token, exists := c.Get("token")
|
|
if !exists {
|
|
c.JSON(http.StatusNotFound, gin.H{"error": "Unauthorized"})
|
|
return
|
|
}
|
|
userToken := token.(*model.Token)
|
|
if userToken.User.Role < int(consts.RoleAdmin) {
|
|
tokens, _, err := h.tokenService.ListsWithFilters(c, 0, 100, map[string]interface{}{"user_id": userToken.UserID})
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
var userDTOs []dto.UserInfo
|
|
for _, token := range tokens {
|
|
userDTOs = append(userDTOs, dto.UserInfo{
|
|
ID: int(token.User.ID),
|
|
Name: token.User.Name,
|
|
Token: token.Key,
|
|
Status: utils.ToPtr(token.User.Status == consts.StatusEnabled),
|
|
})
|
|
}
|
|
c.JSON(http.StatusOK, userDTOs)
|
|
return
|
|
}
|
|
|
|
users, _, err := h.userService.ListUsers(c.Request.Context(), page, pageSize)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
var userDTOs []dto.UserInfo
|
|
for _, user := range users {
|
|
useres := dto.UserInfo{
|
|
ID: int(user.ID),
|
|
Name: user.Name,
|
|
|
|
Status: utils.ToPtr(user.Status == consts.StatusEnabled),
|
|
}
|
|
if len(user.Tokens) > 0 {
|
|
useres.Token = user.Tokens[0].Key
|
|
}
|
|
userDTOs = append(userDTOs, useres)
|
|
}
|
|
|
|
c.JSON(http.StatusOK, userDTOs)
|
|
}
|
|
|
|
func (h *TeamHandler) ResetUserToken(c *gin.Context) {
|
|
idstr := c.Param("id")
|
|
id, err := strconv.Atoi(idstr)
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid user id"})
|
|
return
|
|
}
|
|
token, exists := c.Get("token")
|
|
if !exists {
|
|
c.JSON(http.StatusNotFound, gin.H{"error": "Unauthorized"})
|
|
return
|
|
}
|
|
userToken := token.(*model.Token)
|
|
|
|
findtoken, err := h.tokenService.GetByUserID(c, id)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
findtoken.Key = "team-" + strings.ReplaceAll(uuid.New().String(), "-", "")
|
|
|
|
if userToken.User.Role < int(consts.RoleAdmin) { // 非管理员只能修改自己的token
|
|
if userToken.User.Role <= findtoken.User.Role || userToken.UserID != findtoken.UserID {
|
|
c.JSON(http.StatusForbidden, gin.H{"error": "forbidden"})
|
|
return
|
|
}
|
|
err := h.tokenService.UpdateWithCondition(c, findtoken, map[string]interface{}{"user_id": userToken.UserID}, nil)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
} else {
|
|
if err := h.tokenService.Update(c, findtoken); err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
}
|
|
|
|
c.JSON(http.StatusOK, dto.UserInfo{
|
|
ID: int(findtoken.User.ID),
|
|
Name: findtoken.User.Name,
|
|
Token: findtoken.Key,
|
|
})
|
|
}
|
|
|
|
func (h *TeamHandler) CreateKey(c *gin.Context) {
|
|
token, exists := c.Get("token")
|
|
if !exists {
|
|
c.JSON(http.StatusNotFound, gin.H{"error": "token not found"})
|
|
return
|
|
}
|
|
userToken := token.(*model.Token)
|
|
if userToken.User.Role < int(consts.RoleAdmin) {
|
|
c.JSON(http.StatusForbidden, gin.H{"error": "forbidden"})
|
|
return
|
|
}
|
|
|
|
var key dto.KeyInfo
|
|
if err := c.ShouldBindJSON(&key); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
err := h.keyService.Create(&model.ApiKey{
|
|
Name: key.Name,
|
|
ApiType: key.ApiType,
|
|
ApiKey: key.Key,
|
|
Endpoint: key.Endpoint,
|
|
})
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, key)
|
|
}
|
|
|
|
func (h *TeamHandler) ListKeys(c *gin.Context) {
|
|
keys, err := h.keyService.List(0, 100, nil)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
}
|
|
|
|
var keysDTO []dto.KeyInfo
|
|
for _, key := range keys {
|
|
keylength := len(key.ApiKey) / 3
|
|
if keylength < 1 {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid key length"})
|
|
return
|
|
}
|
|
keysDTO = append(keysDTO, dto.KeyInfo{
|
|
ID: int(key.ID),
|
|
Name: key.Name,
|
|
ApiType: key.ApiType,
|
|
Endpoint: key.Endpoint,
|
|
Key: key.ApiKey[:keylength] + "****" + key.ApiKey[len(key.ApiKey)-keylength:],
|
|
})
|
|
}
|
|
c.JSON(http.StatusOK, keysDTO)
|
|
}
|
|
|
|
func (h *TeamHandler) UpdateKey(c *gin.Context) {
|
|
// 1. 获取并验证ID
|
|
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid key id"})
|
|
return
|
|
}
|
|
|
|
// 2. 解析请求体
|
|
var updateKey dto.KeyInfo // 更明确的命名
|
|
if err := c.ShouldBindJSON(&updateKey); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
// 3. 获取现有记录
|
|
existingKey, err := h.keyService.GetByID(id)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
// 4. 使用 UpdateFields 方法统一处理字段更新
|
|
updatedKey := updateKey.UpdateFields(existingKey)
|
|
|
|
// 5. 保存更新
|
|
if err := h.keyService.Update(updatedKey); err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, updatedKey)
|
|
}
|
|
|
|
func (h *TeamHandler) DeleteKey(c *gin.Context) {
|
|
// 1. 获取并验证ID
|
|
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid key id"})
|
|
return
|
|
}
|
|
|
|
// 2. 删除记录
|
|
if err := h.keyService.Delete(id); err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{"message": "ok"})
|
|
}
|
|
|
|
// ChangePassword 修改密码
|
|
func (h *TeamHandler) ChangePassword(c *gin.Context) {
|
|
userID := c.GetInt64("userID") // 假设从上下文中获取用户ID
|
|
|
|
var req struct {
|
|
OldPassword string `json:"oldPassword"`
|
|
NewPassword string `json:"newPassword"`
|
|
}
|
|
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid input"})
|
|
return
|
|
}
|
|
|
|
if err := h.userService.ChangePassword(c.Request.Context(), userID, req.OldPassword, req.NewPassword); err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{"message": "ok"})
|
|
}
|
|
|
|
// ResetPassword 重置密码
|
|
func (h *TeamHandler) ResetPassword(c *gin.Context) {
|
|
idStr := c.Param("id")
|
|
id, err := strconv.ParseInt(idStr, 10, 64)
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid user id"})
|
|
return
|
|
}
|
|
|
|
operatorID := c.GetInt64("userID") // 假设从上下文中获取操作者ID
|
|
if err := h.userService.ResetPassword(c.Request.Context(), id, operatorID); err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{"message": "password reset successfully"})
|
|
}
|
|
|
|
// EnableUser 启用用户
|
|
func (h *TeamHandler) EnableUser(c *gin.Context) {
|
|
idStr := c.Param("id")
|
|
id, err := strconv.ParseInt(idStr, 10, 64)
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid user id"})
|
|
return
|
|
}
|
|
|
|
operatorID := c.GetInt64("userID") // 假设从上下文中获取操作者ID
|
|
if err := h.userService.EnableUser(c.Request.Context(), id, operatorID); err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{"message": "user enabled successfully"})
|
|
}
|
|
|
|
// DisableUser 禁用用户
|
|
func (h *TeamHandler) DisableUser(c *gin.Context) {
|
|
idStr := c.Param("id")
|
|
id, err := strconv.ParseInt(idStr, 10, 64)
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid user id"})
|
|
return
|
|
}
|
|
|
|
operatorID := c.GetInt64("userID") // 假设从上下文中获取操作者ID
|
|
if err := h.userService.DisableUser(c.Request.Context(), id, operatorID); err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{"message": "user disabled successfully"})
|
|
}
|