diff --git a/api/docs.go b/api/docs.go index 5608df5d..645fe938 100644 --- a/api/docs.go +++ b/api/docs.go @@ -323,24 +323,6 @@ const docTemplate = `{ } }, "/challenges/{id}/attachment": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Challenge" - ], - "summary": "查找附件", - "responses": {} - }, "post": { "security": [ { diff --git a/api/swagger.json b/api/swagger.json index 0ee39076..71dc9d55 100644 --- a/api/swagger.json +++ b/api/swagger.json @@ -314,24 +314,6 @@ } }, "/challenges/{id}/attachment": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Challenge" - ], - "summary": "查找附件", - "responses": {} - }, "post": { "security": [ { diff --git a/api/swagger.yaml b/api/swagger.yaml index 742301b2..870980d8 100644 --- a/api/swagger.yaml +++ b/api/swagger.yaml @@ -1005,17 +1005,6 @@ paths: summary: 删除附件 tags: - Challenge - get: - consumes: - - application/json - produces: - - application/json - responses: {} - security: - - ApiKeyAuth: [] - summary: 查找附件 - tags: - - Challenge post: consumes: - application/json diff --git a/internal/app/db/db.go b/internal/app/db/db.go index 9a175ceb..98a0440f 100644 --- a/internal/app/db/db.go +++ b/internal/app/db/db.go @@ -11,7 +11,6 @@ import ( "gorm.io/driver/postgres" "gorm.io/driver/sqlite" "gorm.io/gorm" - "time" ) var db *gorm.DB @@ -105,11 +104,8 @@ func migrate() { } // selfCheck performs a self-check. -// It updates the removed_at field of the Pod table. -// If the removed_at field is greater than the current time, it is forcibly assigned the current time. -// This is to prevent subsequent program errors in judgment. func selfCheck() { - db.Model(&model.Pod{}).Where("removed_at > ?", time.Now().UnixMilli()).Update("removed_at", time.Now().UnixMilli()) + db.Exec("DELETE FROM pods") } func initAdmin() { diff --git a/internal/controller/challenge.go b/internal/controller/challenge.go index 27ce78ae..6a1f7be5 100644 --- a/internal/controller/challenge.go +++ b/internal/controller/challenge.go @@ -22,7 +22,6 @@ type IChallengeController interface { CreateFlag(ctx *gin.Context) UpdateFlag(ctx *gin.Context) DeleteFlag(ctx *gin.Context) - FindAttachment(ctx *gin.Context) SaveAttachment(ctx *gin.Context) DeleteAttachment(ctx *gin.Context) } @@ -262,31 +261,6 @@ func (c *ChallengeController) DeleteFlag(ctx *gin.Context) { }) } -// FindAttachment -// @Summary 查找附件 -// @Description -// @Tags Challenge -// @Accept json -// @Produce json -// @Security ApiKeyAuth -// @Router /challenges/{id}/attachment [get] -func (c *ChallengeController) FindAttachment(ctx *gin.Context) { - id := convertor.ToUintD(ctx.Param("id"), 0) - filename, size, err := c.mediaService.FindChallengeAttachment(id) - if err != nil { - ctx.JSON(http.StatusBadRequest, gin.H{ - "code": http.StatusBadRequest, - "msg": err.Error(), - }) - return - } - ctx.JSON(http.StatusOK, gin.H{ - "code": http.StatusOK, - "filename": filename, - "size": size, - }) -} - // SaveAttachment // @Summary 保存附件 // @Description diff --git a/internal/controller/game.go b/internal/controller/game.go index 319f8557..d58aa75e 100644 --- a/internal/controller/game.go +++ b/internal/controller/game.go @@ -555,7 +555,7 @@ func (g *GameController) Find(ctx *gin.Context) { return } if ok && isEnabled.(bool) { - gameFindRequest.IsEnabled = convertor.TrueP() + gameFindRequest.IsEnabled = &utils.True } value, exist := cache.C().Get(fmt.Sprintf("games:%s", utils.HashStruct(gameFindRequest))) if !exist { diff --git a/internal/controller/user.go b/internal/controller/user.go index b87a23c6..24c5a25a 100644 --- a/internal/controller/user.go +++ b/internal/controller/user.go @@ -3,16 +3,15 @@ package controller import ( "fmt" "github.com/elabosak233/cloudsdale/internal/extension/cache" - "github.com/elabosak233/cloudsdale/internal/model" "github.com/elabosak233/cloudsdale/internal/model/request" "github.com/elabosak233/cloudsdale/internal/service" "github.com/elabosak233/cloudsdale/internal/utils" "github.com/elabosak233/cloudsdale/internal/utils/convertor" "github.com/elabosak233/cloudsdale/internal/utils/validator" + ginI18n "github.com/gin-contrib/i18n" "github.com/gin-gonic/gin" "go.uber.org/zap" "net/http" - "strings" "time" ) @@ -57,31 +56,18 @@ func (c *UserController) Login(ctx *gin.Context) { }) return } - var user model.User - users, total, err := c.userService.Find(request.UserFindRequest{ - Username: strings.ToLower(userLoginRequest.Username), - }) - if err == nil && total > 0 { - user = users[0] - } else { - ctx.JSON(http.StatusInternalServerError, gin.H{ - "code": http.StatusInternalServerError, - }) - return - } - if !c.userService.VerifyPasswordByUsername(userLoginRequest.Username, userLoginRequest.Password) { + user, token, err := c.userService.Login(userLoginRequest) + if err != nil { ctx.JSON(http.StatusBadRequest, gin.H{ "code": http.StatusBadRequest, - "msg": "用户名或密码错误", + "msg": ginI18n.MustGetMessage(ctx, err.Error()), }) - zap.L().Warn(fmt.Sprintf("User %s login failed", user.Username), zap.Uint("user_id", user.ID)) return } - _ = c.userService.Update(request.UserUpdateRequest{ + err = c.userService.Update(request.UserUpdateRequest{ ID: user.ID, RemoteIP: ctx.RemoteIP(), }) - tokenString, err := c.userService.GetJwtTokenByID(user) if err != nil { ctx.JSON(http.StatusInternalServerError, gin.H{ "code": http.StatusInternalServerError, @@ -92,7 +78,7 @@ func (c *UserController) Login(ctx *gin.Context) { ctx.JSON(http.StatusOK, gin.H{ "code": http.StatusOK, "data": user, - "token": tokenString, + "token": token, }) zap.L().Info(fmt.Sprintf("User %s login successful", user.Username), zap.Uint("user_id", user.ID)) } @@ -106,7 +92,7 @@ func (c *UserController) Login(ctx *gin.Context) { // @Security ApiKeyAuth // @Router /users/logout [post] func (c *UserController) Logout(ctx *gin.Context) { - id, err := c.userService.GetIDByJwtToken(ctx.GetHeader("Authorization")) + id, err := c.userService.Logout(ctx.GetHeader("Authorization")) if err != nil { ctx.JSON(http.StatusBadRequest, gin.H{ "code": http.StatusBadRequest, diff --git a/internal/files/i18n/en.yaml b/internal/files/i18n/en.yaml index b25d9115..8c4abca3 100644 --- a/internal/files/i18n/en.yaml +++ b/internal/files/i18n/en.yaml @@ -1 +1,9 @@ -welcome: welcome \ No newline at end of file +welcome: "welcome" + +user: + not_found: "user not found" + login: + password_incorrect: "password incorrect" + +team: + not_found: "team not found" \ No newline at end of file diff --git a/internal/files/i18n/zh-Hans.yaml b/internal/files/i18n/zh-Hans.yaml index 5c5ae1eb..53d720f9 100644 --- a/internal/files/i18n/zh-Hans.yaml +++ b/internal/files/i18n/zh-Hans.yaml @@ -1 +1,9 @@ -welcome: 欢迎 \ No newline at end of file +welcome: "欢迎" + +user: + not_found: "用户不存在" + login: + password_incorrect: "密码错误" + +team: + not_found: "团队不存在" \ No newline at end of file diff --git a/internal/repository/category.go b/internal/repository/category.go index 4d9641fa..3cfa5a78 100644 --- a/internal/repository/category.go +++ b/internal/repository/category.go @@ -7,10 +7,10 @@ import ( ) type ICategoryRepository interface { - Create(category model.Category) (err error) - Update(category model.Category) (err error) - Find(req request.CategoryFindRequest) (categories []model.Category, err error) - Delete(id uint) (err error) + Create(category model.Category) error + Update(category model.Category) error + Find(req request.CategoryFindRequest) ([]model.Category, error) + Delete(id uint) error } type CategoryRepository struct { @@ -31,7 +31,8 @@ func (t *CategoryRepository) Update(category model.Category) (err error) { return result.Error } -func (t *CategoryRepository) Find(req request.CategoryFindRequest) (categories []model.Category, err error) { +func (t *CategoryRepository) Find(req request.CategoryFindRequest) ([]model.Category, error) { + var categories []model.Category applyFilters := func(db *gorm.DB) *gorm.DB { if req.ID != 0 { db = db.Where("id = ?", req.ID) diff --git a/internal/repository/challenge.go b/internal/repository/challenge.go index 2f26f3a3..8f40fc46 100644 --- a/internal/repository/challenge.go +++ b/internal/repository/challenge.go @@ -21,7 +21,7 @@ func NewChallengeRepository(db *gorm.DB) IChallengeRepository { return &ChallengeRepository{db: db} } -func (t *ChallengeRepository) Create(challenge model.Challenge) (c model.Challenge, err error) { +func (t *ChallengeRepository) Create(challenge model.Challenge) (model.Challenge, error) { result := t.db.Table("challenges").Create(&challenge) return challenge, result.Error } @@ -31,12 +31,13 @@ func (t *ChallengeRepository) Delete(id uint) (err error) { return result.Error } -func (t *ChallengeRepository) Update(challenge model.Challenge) (c model.Challenge, err error) { +func (t *ChallengeRepository) Update(challenge model.Challenge) (model.Challenge, error) { result := t.db.Table("challenges").Model(&challenge).Updates(&challenge) return challenge, result.Error } -func (t *ChallengeRepository) Find(req request.ChallengeFindRequest) (challenges []model.Challenge, total int64, err error) { +func (t *ChallengeRepository) Find(req request.ChallengeFindRequest) ([]model.Challenge, int64, error) { + var challenges []model.Challenge applyFilter := func(q *gorm.DB) *gorm.DB { if req.CategoryID != nil { q = q.Where("category_id = ?", *(req.CategoryID)) @@ -59,7 +60,7 @@ func (t *ChallengeRepository) Find(req request.ChallengeFindRequest) (challenges return q } db := applyFilter(t.db.Table("challenges")) - + var total int64 = 0 result := db.Model(&model.Challenge{}).Count(&total) if req.SortOrder != "" && req.SortKey != "" { db = db.Order(req.SortKey + " " + req.SortOrder) diff --git a/internal/repository/env.go b/internal/repository/env.go index 74344fef..db6ae70a 100644 --- a/internal/repository/env.go +++ b/internal/repository/env.go @@ -6,7 +6,7 @@ import ( ) type IEnvRepository interface { - Create(env model.Env) (e model.Env, err error) + Create(env model.Env) (model.Env, error) } type EnvRepository struct { @@ -17,7 +17,7 @@ func NewEnvRepository(db *gorm.DB) IEnvRepository { return &EnvRepository{db: db} } -func (t *EnvRepository) Create(env model.Env) (e model.Env, err error) { +func (t *EnvRepository) Create(env model.Env) (model.Env, error) { result := t.db.Table("envs"). Create(&env) return env, result.Error diff --git a/internal/repository/flag.go b/internal/repository/flag.go index acc8d2b0..0228baa8 100644 --- a/internal/repository/flag.go +++ b/internal/repository/flag.go @@ -6,9 +6,9 @@ import ( ) type IFlagRepository interface { - Create(flag model.Flag) (f model.Flag, err error) - Update(flag model.Flag) (f model.Flag, err error) - Delete(flag model.Flag) (err error) + Create(flag model.Flag) (model.Flag, error) + Update(flag model.Flag) (model.Flag, error) + Delete(flag model.Flag) error } type FlagRepository struct { @@ -19,17 +19,17 @@ func NewFlagRepository(db *gorm.DB) IFlagRepository { return &FlagRepository{db: db} } -func (t *FlagRepository) Create(flag model.Flag) (f model.Flag, err error) { +func (t *FlagRepository) Create(flag model.Flag) (model.Flag, error) { result := t.db.Table("flags").Create(&flag) return flag, result.Error } -func (t *FlagRepository) Update(flag model.Flag) (f model.Flag, err error) { +func (t *FlagRepository) Update(flag model.Flag) (model.Flag, error) { result := t.db.Table("flags").Model(&flag).Updates(&flag) return flag, result.Error } -func (t *FlagRepository) Delete(flag model.Flag) (err error) { +func (t *FlagRepository) Delete(flag model.Flag) error { result := t.db.Table("flags").Delete(&flag) return result.Error } diff --git a/internal/repository/flag_gen.go b/internal/repository/flag_gen.go index f6048b21..1085ca54 100644 --- a/internal/repository/flag_gen.go +++ b/internal/repository/flag_gen.go @@ -6,8 +6,8 @@ import ( ) type IFlagGenRepository interface { - Create(flag model.FlagGen) (f model.FlagGen, err error) - FindByPodID(podIDs []uint) (flags []model.FlagGen, err error) + Create(flag model.FlagGen) (model.FlagGen, error) + FindByPodID(podIDs []uint) ([]model.FlagGen, error) } type FlagGenRepository struct { @@ -18,12 +18,13 @@ func NewFlagGenRepository(db *gorm.DB) IFlagGenRepository { return &FlagGenRepository{db: db} } -func (t *FlagGenRepository) Create(flag model.FlagGen) (f model.FlagGen, err error) { +func (t *FlagGenRepository) Create(flag model.FlagGen) (model.FlagGen, error) { result := t.db.Table("flag_gens").Create(&flag) return flag, result.Error } -func (t *FlagGenRepository) FindByPodID(podIDs []uint) (flags []model.FlagGen, err error) { +func (t *FlagGenRepository) FindByPodID(podIDs []uint) ([]model.FlagGen, error) { + var flags []model.FlagGen result := t.db.Table("flag_gens"). Where("pod_id IN ?", podIDs). Find(&flags) diff --git a/internal/repository/game.go b/internal/repository/game.go index e949b1c2..93c18f16 100644 --- a/internal/repository/game.go +++ b/internal/repository/game.go @@ -7,10 +7,10 @@ import ( ) type IGameRepository interface { - Create(game model.Game) (g model.Game, err error) - Update(game model.Game) (err error) - Delete(req request.GameDeleteRequest) (err error) - Find(req request.GameFindRequest) (games []model.Game, total int64, err error) + Create(game model.Game) (model.Game, error) + Update(game model.Game) error + Delete(game model.Game) error + Find(req request.GameFindRequest) ([]model.Game, int64, error) } type GameRepository struct { @@ -21,24 +21,23 @@ func NewGameRepository(Db *gorm.DB) IGameRepository { return &GameRepository{Db: Db} } -func (t *GameRepository) Create(game model.Game) (g model.Game, err error) { +func (t *GameRepository) Create(game model.Game) (model.Game, error) { result := t.Db.Table("games").Create(&game) return game, result.Error } -func (t *GameRepository) Update(game model.Game) (err error) { +func (t *GameRepository) Update(game model.Game) error { result := t.Db.Table("games").Model(&game).Updates(&game) return result.Error } -func (t *GameRepository) Delete(req request.GameDeleteRequest) (err error) { - result := t.Db.Table("games").Delete(&model.Game{ - ID: req.ID, - }) +func (t *GameRepository) Delete(game model.Game) error { + result := t.Db.Table("games").Delete(&game) return result.Error } -func (t *GameRepository) Find(req request.GameFindRequest) (games []model.Game, total int64, err error) { +func (t *GameRepository) Find(req request.GameFindRequest) ([]model.Game, int64, error) { + var games []model.Game applyFilters := func(q *gorm.DB) *gorm.DB { if req.ID != 0 { q = q.Where("id = ?", req.ID) @@ -52,7 +51,7 @@ func (t *GameRepository) Find(req request.GameFindRequest) (games []model.Game, return q } db := applyFilters(t.Db.Table("games")) - + var total int64 = 0 result := db.Model(&model.Game{}).Count(&total) if req.SortKey != "" && req.SortOrder != "" { db = db.Order(req.SortKey + " " + req.SortOrder) diff --git a/internal/repository/game_challenge.go b/internal/repository/game_challenge.go index e46bd576..606e172e 100644 --- a/internal/repository/game_challenge.go +++ b/internal/repository/game_challenge.go @@ -7,10 +7,10 @@ import ( ) type IGameChallengeRepository interface { - Find(req request.GameChallengeFindRequest) (gameChallenges []model.GameChallenge, err error) - Create(gameChallenge model.GameChallenge) (err error) - Update(gameChallenge model.GameChallenge) (err error) - Delete(gameChallenge model.GameChallenge) (err error) + Find(req request.GameChallengeFindRequest) ([]model.GameChallenge, error) + Create(gameChallenge model.GameChallenge) error + Update(gameChallenge model.GameChallenge) error + Delete(gameChallenge model.GameChallenge) error } type GameChallengeRepository struct { @@ -21,7 +21,8 @@ func NewGameChallengeRepository(db *gorm.DB) IGameChallengeRepository { return &GameChallengeRepository{db: db} } -func (t *GameChallengeRepository) Find(req request.GameChallengeFindRequest) (gameChallenges []model.GameChallenge, err error) { +func (t *GameChallengeRepository) Find(req request.GameChallengeFindRequest) ([]model.GameChallenge, error) { + var gameChallenges []model.GameChallenge applyFilters := func(q *gorm.DB) *gorm.DB { if req.GameID != 0 { q = q.Where("game_id = ?", req.GameID) @@ -61,12 +62,12 @@ func (t *GameChallengeRepository) Find(req request.GameChallengeFindRequest) (ga return gameChallenges, result.Error } -func (t *GameChallengeRepository) Create(gameChallenge model.GameChallenge) (err error) { +func (t *GameChallengeRepository) Create(gameChallenge model.GameChallenge) error { result := t.db.Table("game_challenges").Create(&gameChallenge) return result.Error } -func (t *GameChallengeRepository) Update(gameChallenge model.GameChallenge) (err error) { +func (t *GameChallengeRepository) Update(gameChallenge model.GameChallenge) error { result := t.db.Table("game_challenges"). Where("challenge_id = ?", gameChallenge.ChallengeID). Where("game_id = ?", gameChallenge.GameID). @@ -75,7 +76,7 @@ func (t *GameChallengeRepository) Update(gameChallenge model.GameChallenge) (err return result.Error } -func (t *GameChallengeRepository) Delete(gameChallenge model.GameChallenge) (err error) { +func (t *GameChallengeRepository) Delete(gameChallenge model.GameChallenge) error { result := t.db.Table("game_challenges"). Where("game_id = ?", gameChallenge.GameID). Where("challenge_id = ?", gameChallenge.ChallengeID). diff --git a/internal/repository/game_team.go b/internal/repository/game_team.go index 9ac1ef77..cd8cda14 100644 --- a/internal/repository/game_team.go +++ b/internal/repository/game_team.go @@ -6,10 +6,10 @@ import ( ) type IGameTeamRepository interface { - Create(gameTeam model.GameTeam) (err error) - Update(gameTeam model.GameTeam) (err error) - Delete(gameTeam model.GameTeam) (err error) - Find(gameTeam model.GameTeam) (gameTeams []model.GameTeam, total int64, err error) + Create(gameTeam model.GameTeam) error + Update(gameTeam model.GameTeam) error + Delete(gameTeam model.GameTeam) error + Find(gameTeam model.GameTeam) ([]model.GameTeam, int64, error) } type GameTeamRepository struct { @@ -20,12 +20,12 @@ func NewGameTeamRepository(db *gorm.DB) IGameTeamRepository { return &GameTeamRepository{db: db} } -func (g *GameTeamRepository) Create(gameTeam model.GameTeam) (err error) { +func (g *GameTeamRepository) Create(gameTeam model.GameTeam) error { result := g.db.Table("game_teams").Create(&gameTeam) return result.Error } -func (g *GameTeamRepository) Delete(gameTeam model.GameTeam) (err error) { +func (g *GameTeamRepository) Delete(gameTeam model.GameTeam) error { result := g.db.Table("game_teams"). Where("game_id = ?", gameTeam.GameID). Where("team_id = ?", gameTeam.TeamID). @@ -33,7 +33,7 @@ func (g *GameTeamRepository) Delete(gameTeam model.GameTeam) (err error) { return result.Error } -func (g *GameTeamRepository) Update(gameTeam model.GameTeam) (err error) { +func (g *GameTeamRepository) Update(gameTeam model.GameTeam) error { result := g.db.Table("game_teams"). Where("game_id = ?", gameTeam.GameID). Where("team_id = ?", gameTeam.TeamID). @@ -42,10 +42,11 @@ func (g *GameTeamRepository) Update(gameTeam model.GameTeam) (err error) { return result.Error } -func (g *GameTeamRepository) Find(gameTeam model.GameTeam) (gameTeams []model.GameTeam, total int64, err error) { +func (g *GameTeamRepository) Find(gameTeam model.GameTeam) ([]model.GameTeam, int64, error) { + var gameTeams []model.GameTeam db := g.db.Table("game_teams"). Where(&gameTeam) - + var total int64 = 0 result := db.Model(&model.GameTeam{}).Count(&total) result = db.Preload("Team", func(db *gorm.DB) *gorm.DB { diff --git a/internal/repository/nat.go b/internal/repository/nat.go index 04cebf0e..9f83f097 100644 --- a/internal/repository/nat.go +++ b/internal/repository/nat.go @@ -6,7 +6,7 @@ import ( ) type INatRepository interface { - Create(nat model.Nat) (n model.Nat, err error) + Create(nat model.Nat) (model.Nat, error) } type NatRepository struct { @@ -17,7 +17,7 @@ func NewNatRepository(db *gorm.DB) INatRepository { return &NatRepository{db: db} } -func (t *NatRepository) Create(nat model.Nat) (n model.Nat, err error) { +func (t *NatRepository) Create(nat model.Nat) (model.Nat, error) { result := t.db.Table("nats").Create(&nat) return nat, result.Error } diff --git a/internal/repository/notice.go b/internal/repository/notice.go index 1aff5776..7ac1b527 100644 --- a/internal/repository/notice.go +++ b/internal/repository/notice.go @@ -7,10 +7,10 @@ import ( ) type INoticeRepository interface { - Find(req request.NoticeFindRequest) (notices []model.Notice, total int64, err error) - Create(notice model.Notice) (n model.Notice, err error) - Update(notice model.Notice) (n model.Notice, err error) - Delete(notice model.Notice) (err error) + Find(req request.NoticeFindRequest) ([]model.Notice, int64, error) + Create(notice model.Notice) (model.Notice, error) + Update(notice model.Notice) (model.Notice, error) + Delete(notice model.Notice) error } type NoticeRepository struct { @@ -21,7 +21,8 @@ func NewNoticeRepository(db *gorm.DB) INoticeRepository { return &NoticeRepository{db: db} } -func (t *NoticeRepository) Find(req request.NoticeFindRequest) (notices []model.Notice, total int64, err error) { +func (t *NoticeRepository) Find(req request.NoticeFindRequest) ([]model.Notice, int64, error) { + var notices []model.Notice applyFilters := func(q *gorm.DB) *gorm.DB { if req.ID != 0 { q = q.Where("id = ?", req.ID) @@ -35,6 +36,7 @@ func (t *NoticeRepository) Find(req request.NoticeFindRequest) (notices []model. return q } db := applyFilters(t.db.Table("notices")) + var total int64 = 0 result := db.Model(&model.Notice{}).Count(&total) db = db.Order("notices.id DESC") result = db. @@ -51,17 +53,17 @@ func (t *NoticeRepository) Find(req request.NoticeFindRequest) (notices []model. return notices, total, result.Error } -func (t *NoticeRepository) Create(notice model.Notice) (n model.Notice, err error) { +func (t *NoticeRepository) Create(notice model.Notice) (model.Notice, error) { result := t.db.Table("notices").Create(¬ice) return notice, result.Error } -func (t *NoticeRepository) Update(notice model.Notice) (n model.Notice, err error) { +func (t *NoticeRepository) Update(notice model.Notice) (model.Notice, error) { result := t.db.Table("notices").Model(¬ice).Updates(¬ice) return notice, result.Error } -func (t *NoticeRepository) Delete(notice model.Notice) (err error) { +func (t *NoticeRepository) Delete(notice model.Notice) error { result := t.db.Table("notices").Delete(¬ice) return result.Error } diff --git a/internal/repository/pod.go b/internal/repository/pod.go index edf718bf..d118ea2d 100644 --- a/internal/repository/pod.go +++ b/internal/repository/pod.go @@ -8,10 +8,9 @@ import ( ) type IPodRepository interface { - Create(pod model.Pod) (i model.Pod, err error) - Update(pod model.Pod) (err error) - Find(req request.PodFindRequest) (pods []model.Pod, total int64, err error) - FindById(id uint) (pod model.Pod, err error) + Create(pod model.Pod) (model.Pod, error) + Update(pod model.Pod) error + Find(req request.PodFindRequest) ([]model.Pod, int64, error) } type PodRepository struct { @@ -22,17 +21,18 @@ func NewPodRepository(db *gorm.DB) IPodRepository { return &PodRepository{db: db} } -func (t *PodRepository) Create(pod model.Pod) (i model.Pod, err error) { +func (t *PodRepository) Create(pod model.Pod) (model.Pod, error) { result := t.db.Table("pods").Create(&pod) return pod, result.Error } -func (t *PodRepository) Update(pod model.Pod) (err error) { +func (t *PodRepository) Update(pod model.Pod) error { result := t.db.Table("pods").Model(&pod).Updates(&pod) return result.Error } -func (t *PodRepository) Find(req request.PodFindRequest) (pods []model.Pod, total int64, err error) { +func (t *PodRepository) Find(req request.PodFindRequest) ([]model.Pod, int64, error) { + var pods []model.Pod applyFilter := func(q *gorm.DB) *gorm.DB { if req.ID != 0 { q = q.Where("id = ?", req.ID) @@ -59,7 +59,7 @@ func (t *PodRepository) Find(req request.PodFindRequest) (pods []model.Pod, tota return q } db := applyFilter(t.db.Table("pods")) - + var total int64 = 0 result := db.Model(&model.Pod{}).Count(&total) if req.Page != 0 && req.Size != 0 { offset := (req.Page - 1) * req.Size @@ -77,8 +77,3 @@ func (t *PodRepository) Find(req request.PodFindRequest) (pods []model.Pod, tota Find(&pods) return pods, total, result.Error } - -func (t *PodRepository) FindById(id uint) (pod model.Pod, err error) { - result := t.db.Table("pods").First(&model.Pod{ID: id}) - return pod, result.Error -} diff --git a/internal/repository/port.go b/internal/repository/port.go index 4663fd6c..bbc89e0f 100644 --- a/internal/repository/port.go +++ b/internal/repository/port.go @@ -6,9 +6,9 @@ import ( ) type IPortRepository interface { - Create(port model.Port) (p model.Port, err error) - Update(port model.Port) (p model.Port, err error) - Delete(port model.Port) (err error) + Create(port model.Port) (model.Port, error) + Update(port model.Port) (model.Port, error) + Delete(port model.Port) error } type PortRepository struct { @@ -19,17 +19,17 @@ func NewPortRepository(db *gorm.DB) IPortRepository { return &PortRepository{db: db} } -func (t *PortRepository) Create(port model.Port) (p model.Port, err error) { +func (t *PortRepository) Create(port model.Port) (model.Port, error) { result := t.db.Table("ports").Create(&port) return port, result.Error } -func (t *PortRepository) Update(port model.Port) (p model.Port, err error) { +func (t *PortRepository) Update(port model.Port) (model.Port, error) { result := t.db.Table("ports").Model(&port).Updates(&port) return port, result.Error } -func (t *PortRepository) Delete(port model.Port) (err error) { +func (t *PortRepository) Delete(port model.Port) error { result := t.db.Table("ports").Delete(&port) return result.Error } diff --git a/internal/repository/submission.go b/internal/repository/submission.go index 48cee1da..c46638bd 100644 --- a/internal/repository/submission.go +++ b/internal/repository/submission.go @@ -7,9 +7,9 @@ import ( ) type ISubmissionRepository interface { - Create(submission model.Submission) (err error) - Delete(id uint) (err error) - Find(req request.SubmissionFindRequest) (submissions []model.Submission, count int64, err error) + Create(submission model.Submission) error + Delete(id uint) error + Find(req request.SubmissionFindRequest) ([]model.Submission, int64, error) } type SubmissionRepository struct { @@ -20,17 +20,18 @@ func NewSubmissionRepository(db *gorm.DB) ISubmissionRepository { return &SubmissionRepository{db: db} } -func (t *SubmissionRepository) Create(submission model.Submission) (err error) { +func (t *SubmissionRepository) Create(submission model.Submission) error { result := t.db.Table("submissions").Create(&submission) return result.Error } -func (t *SubmissionRepository) Delete(id uint) (err error) { +func (t *SubmissionRepository) Delete(id uint) error { result := t.db.Table("submissions").Delete(&model.Submission{ID: id}) return result.Error } -func (t *SubmissionRepository) Find(req request.SubmissionFindRequest) (submissions []model.Submission, total int64, err error) { +func (t *SubmissionRepository) Find(req request.SubmissionFindRequest) ([]model.Submission, int64, error) { + var submissions []model.Submission applyFilters := func(q *gorm.DB) *gorm.DB { if req.UserID != 0 && req.TeamID == nil && req.GameID == nil { q = q.Where("user_id = ?", req.UserID) @@ -50,7 +51,7 @@ func (t *SubmissionRepository) Find(req request.SubmissionFindRequest) (submissi return q } db := applyFilters(t.db.Table("submissions")) - + var total int64 = 0 result := db.Model(&model.Submission{}).Count(&total) if req.SortKey != "" && req.SortOrder != "" { db = db.Order(req.SortKey + " " + req.SortOrder) diff --git a/internal/repository/team.go b/internal/repository/team.go index 7764114a..618ee5f6 100644 --- a/internal/repository/team.go +++ b/internal/repository/team.go @@ -7,11 +7,11 @@ import ( ) type ITeamRepository interface { - Create(team model.Team) (te model.Team, err error) - Update(team model.Team) (err error) - Delete(id uint) (err error) - Find(req request.TeamFindRequest) (teams []model.Team, count int64, err error) - FindById(id uint) (team model.Team, err error) + Create(team model.Team) (model.Team, error) + Update(team model.Team) error + Delete(id uint) error + Find(req request.TeamFindRequest) ([]model.Team, int64, error) + FindById(id uint) (model.Team, error) } type TeamRepository struct { @@ -22,24 +22,25 @@ func NewTeamRepository(db *gorm.DB) ITeamRepository { return &TeamRepository{db: db} } -func (t *TeamRepository) Create(team model.Team) (te model.Team, err error) { +func (t *TeamRepository) Create(team model.Team) (model.Team, error) { result := t.db.Table("teams").Create(&team) return team, result.Error } -func (t *TeamRepository) Update(team model.Team) (err error) { +func (t *TeamRepository) Update(team model.Team) error { result := t.db.Table("teams").Model(&team).Updates(&team) return result.Error } -func (t *TeamRepository) Delete(id uint) (err error) { +func (t *TeamRepository) Delete(id uint) error { result := t.db.Table("teams").Where("id = ?", id).Delete(&model.Team{ ID: id, }) return result.Error } -func (t *TeamRepository) Find(req request.TeamFindRequest) (teams []model.Team, total int64, err error) { +func (t *TeamRepository) Find(req request.TeamFindRequest) ([]model.Team, int64, error) { + var teams []model.Team applyFilters := func(q *gorm.DB) *gorm.DB { if req.ID != 0 { q = q.Where("id = ?", req.ID) @@ -61,7 +62,7 @@ func (t *TeamRepository) Find(req request.TeamFindRequest) (teams []model.Team, return q } db := applyFilters(t.db.Table("teams")) - + var total int64 = 0 result := db.Model(&model.Team{}).Count(&total) if req.SortKey != "" && req.SortOrder != "" { db = db.Order(req.SortKey + " " + req.SortOrder) @@ -84,7 +85,8 @@ func (t *TeamRepository) Find(req request.TeamFindRequest) (teams []model.Team, return teams, total, result.Error } -func (t *TeamRepository) FindById(id uint) (team model.Team, err error) { +func (t *TeamRepository) FindById(id uint) (model.Team, error) { + var team model.Team result := t.db.Table("teams").Where("id = ?", id).First(&team) return team, result.Error } diff --git a/internal/repository/user.go b/internal/repository/user.go index 112f1c41..480f04fa 100644 --- a/internal/repository/user.go +++ b/internal/repository/user.go @@ -10,9 +10,9 @@ type IUserRepository interface { Create(user model.User) error Update(user model.User) error Delete(id uint) error - FindById(id uint) (user model.User, err error) - FindByUsername(username string) (user model.User, err error) - Find(req request.UserFindRequest) (user []model.User, total int64, err error) + FindById(id uint) (model.User, error) + FindByUsername(username string) (model.User, error) + Find(req request.UserFindRequest) ([]model.User, int64, error) } type UserRepository struct { @@ -40,7 +40,8 @@ func (t *UserRepository) Update(user model.User) error { return result.Error } -func (t *UserRepository) Find(req request.UserFindRequest) (users []model.User, total int64, err error) { +func (t *UserRepository) Find(req request.UserFindRequest) ([]model.User, int64, error) { + var users []model.User applyFilter := func(q *gorm.DB) *gorm.DB { if req.ID != 0 { q = q.Where("id = ?", req.ID) @@ -60,6 +61,7 @@ func (t *UserRepository) Find(req request.UserFindRequest) (users []model.User, return q } db := applyFilter(t.db.Table("users")) + var total int64 = 0 result := db.Model(&model.User{}).Count(&total) if req.SortKey != "" && req.SortOrder != "" { db = db.Order(req.SortKey + " " + req.SortOrder) @@ -76,7 +78,8 @@ func (t *UserRepository) Find(req request.UserFindRequest) (users []model.User, return users, total, result.Error } -func (t *UserRepository) FindById(id uint) (user model.User, err error) { +func (t *UserRepository) FindById(id uint) (model.User, error) { + var user model.User result := t.db.Table("users"). Where("id = ?", id). Preload("Teams"). @@ -84,7 +87,8 @@ func (t *UserRepository) FindById(id uint) (user model.User, err error) { return user, result.Error } -func (t *UserRepository) FindByUsername(username string) (user model.User, err error) { +func (t *UserRepository) FindByUsername(username string) (model.User, error) { + var user model.User result := t.db.Table("users"). Where("username = ?", username). Preload("Teams"). diff --git a/internal/router/challenge.go b/internal/router/challenge.go index 7464004d..03506b32 100644 --- a/internal/router/challenge.go +++ b/internal/router/challenge.go @@ -3,6 +3,7 @@ package router import ( "github.com/elabosak233/cloudsdale/internal/controller" "github.com/elabosak233/cloudsdale/internal/model" + "github.com/elabosak233/cloudsdale/internal/utils" "github.com/elabosak233/cloudsdale/internal/utils/convertor" "github.com/gin-gonic/gin" ) @@ -31,7 +32,6 @@ func (c *ChallengeRouter) Register() { c.router.POST("/:id/flags", c.controller.CreateFlag) c.router.PUT("/:id/flags/:flag_id", c.controller.UpdateFlag) c.router.DELETE("/:id/flags/:flag_id", c.controller.DeleteFlag) - c.router.GET("/:id/attachment", c.controller.FindAttachment) c.router.POST("/:id/attachment", c.controller.SaveAttachment) c.router.DELETE("/:id/attachment", c.controller.DeleteAttachment) } @@ -47,7 +47,7 @@ func (c *ChallengeRouter) PreProcess() gin.HandlerFunc { if user.Group == "admin" { ctx.Set("is_practicable", convertor.ToBoolP(ctx.Query("is_practicable"))) } else { - ctx.Set("is_practicable", convertor.TrueP()) + ctx.Set("is_practicable", &utils.True) } ctx.Next() } diff --git a/internal/service/challenge.go b/internal/service/challenge.go index 581d6e7d..3ecbe5e3 100644 --- a/internal/service/challenge.go +++ b/internal/service/challenge.go @@ -8,10 +8,10 @@ import ( ) type IChallengeService interface { - Find(req request.ChallengeFindRequest) (challenges []model.Challenge, total int64, err error) - Create(req request.ChallengeCreateRequest) (err error) - Update(req request.ChallengeUpdateRequest) (err error) - Delete(id uint) (err error) + Find(req request.ChallengeFindRequest) ([]model.Challenge, int64, error) + Create(req request.ChallengeCreateRequest) error + Update(req request.ChallengeUpdateRequest) error + Delete(id uint) error } type ChallengeService struct { @@ -36,27 +36,27 @@ func NewChallengeService(r *repository.Repository) IChallengeService { } } -func (t *ChallengeService) Create(req request.ChallengeCreateRequest) (err error) { +func (t *ChallengeService) Create(req request.ChallengeCreateRequest) error { challenge := model.Challenge{} _ = mapstructure.Decode(req, &challenge) - _, err = t.challengeRepository.Create(challenge) + _, err := t.challengeRepository.Create(challenge) return err } -func (t *ChallengeService) Update(req request.ChallengeUpdateRequest) (err error) { +func (t *ChallengeService) Update(req request.ChallengeUpdateRequest) error { challenge := model.Challenge{} _ = mapstructure.Decode(req, &challenge) - challenge, err = t.challengeRepository.Update(challenge) + challenge, err := t.challengeRepository.Update(challenge) return err } -func (t *ChallengeService) Delete(id uint) (err error) { - err = t.challengeRepository.Delete(id) +func (t *ChallengeService) Delete(id uint) error { + err := t.challengeRepository.Delete(id) return err } -func (t *ChallengeService) Find(req request.ChallengeFindRequest) (challenges []model.Challenge, total int64, err error) { - challenges, total, err = t.challengeRepository.Find(req) +func (t *ChallengeService) Find(req request.ChallengeFindRequest) ([]model.Challenge, int64, error) { + challenges, total, err := t.challengeRepository.Find(req) for index, challenge := range challenges { if !*(req.IsDetailed) { diff --git a/internal/service/config.go b/internal/service/config.go index 40ae8b5a..28334092 100644 --- a/internal/service/config.go +++ b/internal/service/config.go @@ -6,7 +6,7 @@ import ( ) type IConfigService interface { - Update(req request.ConfigUpdateRequest) (err error) + Update(req request.ConfigUpdateRequest) error } type ConfigService struct { @@ -16,7 +16,7 @@ func NewConfigService() IConfigService { return &ConfigService{} } -func (c *ConfigService) Update(req request.ConfigUpdateRequest) (err error) { +func (c *ConfigService) Update(req request.ConfigUpdateRequest) error { config.PltCfg().Site.Title = req.Site.Title config.PltCfg().Site.Description = req.Site.Description config.PltCfg().Container.ParallelLimit = req.Container.ParallelLimit @@ -24,6 +24,6 @@ func (c *ConfigService) Update(req request.ConfigUpdateRequest) (err error) { config.PltCfg().User.Register.Enabled = req.User.Register.Enabled config.PltCfg().User.Register.Captcha.Enabled = req.User.Register.Captcha.Enabled config.PltCfg().User.Register.Email.Enabled = req.User.Register.Email.Enabled - err = config.PltCfg().Save() + err := config.PltCfg().Save() return err } diff --git a/internal/service/flag.go b/internal/service/flag.go index 39d52040..5725c328 100644 --- a/internal/service/flag.go +++ b/internal/service/flag.go @@ -8,9 +8,9 @@ import ( ) type IFlagService interface { - Create(req request.FlagCreateRequest) (err error) - Update(req request.FlagUpdateRequest) (err error) - Delete(req request.FlagDeleteRequest) (err error) + Create(req request.FlagCreateRequest) error + Update(req request.FlagUpdateRequest) error + Delete(req request.FlagDeleteRequest) error } type FlagService struct { @@ -23,23 +23,23 @@ func NewFlagService(r *repository.Repository) IFlagService { } } -func (f *FlagService) Create(req request.FlagCreateRequest) (err error) { +func (f *FlagService) Create(req request.FlagCreateRequest) error { var flag model.Flag _ = mapstructure.Decode(req, &flag) - _, err = f.flagRepository.Create(flag) + _, err := f.flagRepository.Create(flag) return err } -func (f *FlagService) Update(req request.FlagUpdateRequest) (err error) { +func (f *FlagService) Update(req request.FlagUpdateRequest) error { var flag model.Flag _ = mapstructure.Decode(req, &flag) - _, err = f.flagRepository.Update(flag) - return + _, err := f.flagRepository.Update(flag) + return err } -func (f *FlagService) Delete(req request.FlagDeleteRequest) (err error) { +func (f *FlagService) Delete(req request.FlagDeleteRequest) error { var flag model.Flag _ = mapstructure.Decode(req, &flag) - err = f.flagRepository.Delete(flag) - return + err := f.flagRepository.Delete(flag) + return err } diff --git a/internal/service/game.go b/internal/service/game.go index 3bc56a4f..090cc3c6 100644 --- a/internal/service/game.go +++ b/internal/service/game.go @@ -58,7 +58,9 @@ func (g *GameService) Update(req request.GameUpdateRequest) (err error) { } func (g *GameService) Delete(req request.GameDeleteRequest) (err error) { - return g.gameRepository.Delete(req) + return g.gameRepository.Delete(model.Game{ + ID: req.ID, + }) } func (g *GameService) Find(req request.GameFindRequest) (games []model.Game, total int64, err error) { diff --git a/internal/service/game_challenge.go b/internal/service/game_challenge.go index 55ba9c71..ef545310 100644 --- a/internal/service/game_challenge.go +++ b/internal/service/game_challenge.go @@ -9,10 +9,10 @@ import ( ) type IGameChallengeService interface { - Find(req request.GameChallengeFindRequest) (challenges []model.GameChallenge, err error) - Create(req request.GameChallengeCreateRequest) (err error) - Update(req request.GameChallengeUpdateRequest) (err error) - Delete(req request.GameChallengeDeleteRequest) (err error) + Find(req request.GameChallengeFindRequest) ([]model.GameChallenge, error) + Create(req request.GameChallengeCreateRequest) error + Update(req request.GameChallengeUpdateRequest) error + Delete(req request.GameChallengeDeleteRequest) error } type GameChallengeService struct { @@ -29,12 +29,12 @@ func NewGameChallengeService(r *repository.Repository) IGameChallengeService { } } -func (g *GameChallengeService) Find(req request.GameChallengeFindRequest) (gameChallenges []model.GameChallenge, err error) { +func (g *GameChallengeService) Find(req request.GameChallengeFindRequest) ([]model.GameChallenge, error) { games, _, _ := g.gameRepository.Find(request.GameFindRequest{ ID: req.GameID, }) game := games[0] - gameChallenges, err = g.gameChallengeRepository.Find(req) + gameChallenges, err := g.gameChallengeRepository.Find(req) for i, gameChallenge := range gameChallenges { pts := calculate.GameChallengePts( gameChallenge.MaxPts, @@ -73,16 +73,16 @@ func (g *GameChallengeService) Find(req request.GameChallengeFindRequest) (gameC return gameChallenges, err } -func (g *GameChallengeService) Create(req request.GameChallengeCreateRequest) (err error) { +func (g *GameChallengeService) Create(req request.GameChallengeCreateRequest) error { var gameChallenge model.GameChallenge - err = mapstructure.Decode(req, &gameChallenge) + err := mapstructure.Decode(req, &gameChallenge) err = g.gameChallengeRepository.Create(gameChallenge) return err } -func (g *GameChallengeService) Update(req request.GameChallengeUpdateRequest) (err error) { +func (g *GameChallengeService) Update(req request.GameChallengeUpdateRequest) error { var gameChallenge model.GameChallenge - err = mapstructure.Decode(req, &gameChallenge) + err := mapstructure.Decode(req, &gameChallenge) err = g.gameChallengeRepository.Update(gameChallenge) if gameChallenge.IsEnabled != nil && *(gameChallenge.IsEnabled) { _, err = g.noticeRepository.Create(model.Notice{ @@ -94,9 +94,9 @@ func (g *GameChallengeService) Update(req request.GameChallengeUpdateRequest) (e return err } -func (g *GameChallengeService) Delete(req request.GameChallengeDeleteRequest) (err error) { +func (g *GameChallengeService) Delete(req request.GameChallengeDeleteRequest) error { var gameChallenge model.GameChallenge - err = mapstructure.Decode(req, &gameChallenge) + err := mapstructure.Decode(req, &gameChallenge) err = g.gameChallengeRepository.Delete(gameChallenge) return err } diff --git a/internal/service/game_team.go b/internal/service/game_team.go index ea30223e..1a242d4c 100644 --- a/internal/service/game_team.go +++ b/internal/service/game_team.go @@ -12,10 +12,10 @@ import ( ) type IGameTeamService interface { - Find(req request.GameTeamFindRequest) (teams []model.GameTeam, total int64, err error) - Create(req request.GameTeamCreateRequest) (err error) - Update(req request.GameTeamUpdateRequest) (err error) - Delete(req request.GameTeamDeleteRequest) (err error) + Find(req request.GameTeamFindRequest) ([]model.GameTeam, int64, error) + Create(req request.GameTeamCreateRequest) error + Update(req request.GameTeamUpdateRequest) error + Delete(req request.GameTeamDeleteRequest) error } type GameTeamService struct { @@ -36,7 +36,7 @@ func NewGameTeamService(r *repository.Repository) IGameTeamService { } } -func (g *GameTeamService) Find(req request.GameTeamFindRequest) (teams []model.GameTeam, total int64, err error) { +func (g *GameTeamService) Find(req request.GameTeamFindRequest) ([]model.GameTeam, int64, error) { gameTeams, total, err := g.gameTeamRepository.Find(model.GameTeam{ GameID: req.GameID, TeamID: req.TeamID, @@ -50,7 +50,7 @@ func (g *GameTeamService) Find(req request.GameTeamFindRequest) (teams []model.G return gameTeams, total, err } -func (g *GameTeamService) Create(req request.GameTeamCreateRequest) (err error) { +func (g *GameTeamService) Create(req request.GameTeamCreateRequest) error { games, _, err := g.gameRepository.Find(request.GameFindRequest{ ID: req.ID, }) @@ -106,16 +106,16 @@ func (g *GameTeamService) Create(req request.GameTeamCreateRequest) (err error) return err } -func (g *GameTeamService) Update(req request.GameTeamUpdateRequest) (err error) { +func (g *GameTeamService) Update(req request.GameTeamUpdateRequest) error { var gameTeam model.GameTeam - err = mapstructure.Decode(req, &gameTeam) + err := mapstructure.Decode(req, &gameTeam) err = g.gameTeamRepository.Update(gameTeam) return err } -func (g *GameTeamService) Delete(req request.GameTeamDeleteRequest) (err error) { +func (g *GameTeamService) Delete(req request.GameTeamDeleteRequest) error { var gameTeam model.GameTeam - err = mapstructure.Decode(req, &gameTeam) + err := mapstructure.Decode(req, &gameTeam) err = g.gameTeamRepository.Delete(gameTeam) return err } diff --git a/internal/service/media.go b/internal/service/media.go index e7d764f8..f6368999 100644 --- a/internal/service/media.go +++ b/internal/service/media.go @@ -10,15 +10,14 @@ import ( ) type IMediaService interface { - SaveGamePoster(id uint, fileHeader *multipart.FileHeader) (err error) - DeleteGamePoster(id uint) (err error) - SaveUserAvatar(id uint, fileHeader *multipart.FileHeader) (err error) - DeleteUserAvatar(id uint) (err error) - SaveTeamAvatar(id uint, fileHeader *multipart.FileHeader) (err error) - DeleteTeamAvatar(id uint) (err error) - FindChallengeAttachment(id uint) (filename string, size int64, err error) - SaveChallengeAttachment(id uint, fileHeader *multipart.FileHeader) (err error) - DeleteChallengeAttachment(id uint) (err error) + SaveGamePoster(id uint, fileHeader *multipart.FileHeader) error + DeleteGamePoster(id uint) error + SaveUserAvatar(id uint, fileHeader *multipart.FileHeader) error + DeleteUserAvatar(id uint) error + SaveTeamAvatar(id uint, fileHeader *multipart.FileHeader) error + DeleteTeamAvatar(id uint) error + SaveChallengeAttachment(id uint, fileHeader *multipart.FileHeader) error + DeleteChallengeAttachment(id uint) error } type MediaService struct{} @@ -27,19 +26,7 @@ func NewMediaService() IMediaService { return &MediaService{} } -func (m *MediaService) FindChallengeAttachment(id uint) (filename string, size int64, err error) { - p := path.Join(utils.MediaPath, "challenges", fmt.Sprintf("%d", id)) - files, err := os.ReadDir(p) - for _, file := range files { - filename = file.Name() - info, _ := file.Info() - size = info.Size() - break - } - return filename, size, err -} - -func (m *MediaService) SaveChallengeAttachment(id uint, fileHeader *multipart.FileHeader) (err error) { +func (m *MediaService) SaveChallengeAttachment(id uint, fileHeader *multipart.FileHeader) error { file, err := fileHeader.Open() defer func(file multipart.File) { _ = file.Close() @@ -57,12 +44,12 @@ func (m *MediaService) SaveChallengeAttachment(id uint, fileHeader *multipart.Fi return err } -func (m *MediaService) DeleteChallengeAttachment(id uint) (err error) { +func (m *MediaService) DeleteChallengeAttachment(id uint) error { p := path.Join(utils.MediaPath, "challenges", fmt.Sprintf("%d", id)) return os.RemoveAll(p) } -func (m *MediaService) SaveGamePoster(id uint, fileHeader *multipart.FileHeader) (err error) { +func (m *MediaService) SaveGamePoster(id uint, fileHeader *multipart.FileHeader) error { file, err := fileHeader.Open() defer func(file multipart.File) { _ = file.Close() @@ -80,12 +67,12 @@ func (m *MediaService) SaveGamePoster(id uint, fileHeader *multipart.FileHeader) return err } -func (m *MediaService) DeleteGamePoster(id uint) (err error) { +func (m *MediaService) DeleteGamePoster(id uint) error { p := path.Join(utils.MediaPath, "games", fmt.Sprintf("%d", id), "poster") return os.RemoveAll(p) } -func (m *MediaService) SaveUserAvatar(id uint, fileHeader *multipart.FileHeader) (err error) { +func (m *MediaService) SaveUserAvatar(id uint, fileHeader *multipart.FileHeader) error { file, err := fileHeader.Open() defer func(file multipart.File) { _ = file.Close() @@ -103,12 +90,12 @@ func (m *MediaService) SaveUserAvatar(id uint, fileHeader *multipart.FileHeader) return err } -func (m *MediaService) DeleteUserAvatar(id uint) (err error) { +func (m *MediaService) DeleteUserAvatar(id uint) error { p := path.Join(utils.MediaPath, "users", fmt.Sprintf("%d", id)) return os.RemoveAll(p) } -func (m *MediaService) SaveTeamAvatar(id uint, fileHeader *multipart.FileHeader) (err error) { +func (m *MediaService) SaveTeamAvatar(id uint, fileHeader *multipart.FileHeader) error { file, err := fileHeader.Open() defer func(file multipart.File) { _ = file.Close() @@ -126,7 +113,7 @@ func (m *MediaService) SaveTeamAvatar(id uint, fileHeader *multipart.FileHeader) return err } -func (m *MediaService) DeleteTeamAvatar(id uint) (err error) { +func (m *MediaService) DeleteTeamAvatar(id uint) error { p := path.Join(utils.MediaPath, "teams", fmt.Sprintf("%d", id)) return os.RemoveAll(p) } diff --git a/internal/service/notice.go b/internal/service/notice.go index 42e957a9..f8c57a71 100644 --- a/internal/service/notice.go +++ b/internal/service/notice.go @@ -8,10 +8,10 @@ import ( ) type INoticeService interface { - Find(req request.NoticeFindRequest) (notices []model.Notice, total int64, err error) - Create(req request.NoticeCreateRequest) (err error) - Update(req request.NoticeUpdateRequest) (err error) - Delete(req request.NoticeDeleteRequest) (err error) + Find(req request.NoticeFindRequest) ([]model.Notice, int64, error) + Create(req request.NoticeCreateRequest) error + Update(req request.NoticeUpdateRequest) error + Delete(req request.NoticeDeleteRequest) error } type NoticeService struct { @@ -24,28 +24,28 @@ func NewNoticeService(r *repository.Repository) INoticeService { } } -func (n *NoticeService) Find(req request.NoticeFindRequest) (notices []model.Notice, total int64, err error) { - notices, total, err = n.noticeRepository.Find(req) +func (n *NoticeService) Find(req request.NoticeFindRequest) ([]model.Notice, int64, error) { + notices, total, err := n.noticeRepository.Find(req) return notices, total, err } -func (n *NoticeService) Create(req request.NoticeCreateRequest) (err error) { +func (n *NoticeService) Create(req request.NoticeCreateRequest) error { var notice model.Notice _ = mapstructure.Decode(req, ¬ice) - _, err = n.noticeRepository.Create(notice) + _, err := n.noticeRepository.Create(notice) return err } -func (n *NoticeService) Update(req request.NoticeUpdateRequest) (err error) { +func (n *NoticeService) Update(req request.NoticeUpdateRequest) error { var notice model.Notice _ = mapstructure.Decode(req, ¬ice) - _, err = n.noticeRepository.Update(notice) + _, err := n.noticeRepository.Update(notice) return err } -func (n *NoticeService) Delete(req request.NoticeDeleteRequest) (err error) { +func (n *NoticeService) Delete(req request.NoticeDeleteRequest) error { var notice model.Notice _ = mapstructure.Decode(req, ¬ice) - err = n.noticeRepository.Delete(notice) - return + err := n.noticeRepository.Delete(notice) + return err } diff --git a/internal/service/pod.go b/internal/service/pod.go index 016c126d..58d2f1cf 100644 --- a/internal/service/pod.go +++ b/internal/service/pod.go @@ -9,7 +9,6 @@ import ( "github.com/elabosak233/cloudsdale/internal/model/request" "github.com/elabosak233/cloudsdale/internal/repository" "github.com/elabosak233/cloudsdale/internal/utils" - "github.com/elabosak233/cloudsdale/internal/utils/convertor" "strings" "sync" "time" @@ -89,13 +88,13 @@ func (t *PodService) ParallelLimit(req request.PodCreateRequest) { if !isGame { availablePods, count, _ = t.podRepository.Find(request.PodFindRequest{ UserID: &req.UserID, - IsAvailable: convertor.TrueP(), + IsAvailable: &utils.True, }) } else { availablePods, count, _ = t.podRepository.Find(request.PodFindRequest{ TeamID: req.TeamID, GameID: req.GameID, - IsAvailable: convertor.TrueP(), + IsAvailable: &utils.True, }) } needToBeDeactivated := count - int64(config.PltCfg().Container.ParallelLimit) + 1 @@ -123,7 +122,7 @@ func (t *PodService) Create(req request.PodCreateRequest) (model.Pod, error) { SetUserInstanceRequestMap(req.UserID, time.Now().Unix()) challenges, _, _ := t.challengeRepository.Find(request.ChallengeFindRequest{ ID: req.ChallengeID, - IsDynamic: convertor.TrueP(), + IsDynamic: &utils.True, }) challenge := challenges[0] @@ -190,7 +189,13 @@ func (t *PodService) Renew(req request.PodRenewRequest) error { return errors.New(fmt.Sprintf("请等待 %d 秒后再次请求", remainder)) } SetUserInstanceRequestMap(req.UserID, time.Now().Unix()) // 保存用户请求时间 - pod, _ := t.podRepository.FindById(req.ID) + pods, total, _ := t.podRepository.Find(request.PodFindRequest{ + ID: req.ID, + }) + if total == 0 { + return errors.New("实例不存在") + } + pod := pods[0] ctn, ok := PodManagers[req.ID] if !ok { return errors.New("实例不存在") diff --git a/internal/service/submission.go b/internal/service/submission.go index 7cc3a441..58ea1a6c 100644 --- a/internal/service/submission.go +++ b/internal/service/submission.go @@ -4,8 +4,8 @@ import ( "github.com/elabosak233/cloudsdale/internal/model" "github.com/elabosak233/cloudsdale/internal/model/request" "github.com/elabosak233/cloudsdale/internal/repository" + "github.com/elabosak233/cloudsdale/internal/utils" "github.com/elabosak233/cloudsdale/internal/utils/calculate" - "github.com/elabosak233/cloudsdale/internal/utils/convertor" "regexp" "time" ) @@ -13,7 +13,7 @@ import ( type ISubmissionService interface { Create(req request.SubmissionCreateRequest) (status int, rank int64, err error) Delete(id uint) (err error) - Find(req request.SubmissionFindRequest) (submissions []model.Submission, total int64, err error) + Find(req request.SubmissionFindRequest) ([]model.Submission, int64, error) } type SubmissionService struct { @@ -46,7 +46,7 @@ func (t *SubmissionService) JudgeDynamicChallenge(req request.SubmissionCreateRe perhapsPods, _, err := t.podRepository.Find(request.PodFindRequest{ ChallengeID: req.ChallengeID, GameID: req.GameID, - IsAvailable: convertor.TrueP(), + IsAvailable: &utils.True, }) status = 1 podIDs := make([]uint, 0) @@ -195,13 +195,13 @@ func (t *SubmissionService) Create(req request.SubmissionCreateRequest) (status return status, rank, err } -func (t *SubmissionService) Delete(id uint) (err error) { - err = t.submissionRepository.Delete(id) +func (t *SubmissionService) Delete(id uint) error { + err := t.submissionRepository.Delete(id) return err } -func (t *SubmissionService) Find(req request.SubmissionFindRequest) (submissions []model.Submission, total int64, err error) { - submissions, total, err = t.submissionRepository.Find(req) +func (t *SubmissionService) Find(req request.SubmissionFindRequest) ([]model.Submission, int64, error) { + submissions, total, err := t.submissionRepository.Find(req) challengeSolvesTotal := make(map[uint]int64) extractChallengeTotal := func(challengeID uint) int64 { diff --git a/internal/service/team.go b/internal/service/team.go index cf1b791d..93e84f5f 100644 --- a/internal/service/team.go +++ b/internal/service/team.go @@ -9,13 +9,23 @@ import ( ) type ITeamService interface { + // Create will create a team with the given request. Create(req request.TeamCreateRequest) error + + // Update will update a team with the given id. Update(req request.TeamUpdateRequest) error + + // Delete will delete a team with the given id. Delete(id uint) error - Find(req request.TeamFindRequest) (teams []model.Team, total int64, err error) - FindById(id uint) (team model.Team, err error) - GetInviteToken(req request.TeamGetInviteTokenRequest) (token string, err error) - UpdateInviteToken(req request.TeamUpdateInviteTokenRequest) (token string, err error) + + // Find will return the teams, total count and error. + Find(req request.TeamFindRequest) ([]model.Team, int64, error) + + // GetInviteToken will return the invite token of the team. + GetInviteToken(req request.TeamGetInviteTokenRequest) (string, error) + + // UpdateInviteToken will update the invite token of the team. + UpdateInviteToken(req request.TeamUpdateInviteTokenRequest) (string, error) } type TeamService struct { @@ -35,7 +45,7 @@ func NewTeamService(r *repository.Repository) ITeamService { func (t *TeamService) Create(req request.TeamCreateRequest) error { user, err := t.userRepository.FindById(req.CaptainId) if err != nil || user.ID == 0 { - return errors.New("用户不存在") + return errors.New("user.not_found") } isLocked := false uid := uuid.NewString() @@ -53,7 +63,7 @@ func (t *TeamService) Create(req request.TeamCreateRequest) error { func (t *TeamService) Update(req request.TeamUpdateRequest) error { team, err := t.teamRepository.FindById(req.ID) if err != nil || team.ID == 0 { - return errors.New("团队不存在") + return errors.New("team.not_found") } err = t.teamRepository.Update(model.Team{ ID: team.ID, @@ -69,14 +79,14 @@ func (t *TeamService) Update(req request.TeamUpdateRequest) error { func (t *TeamService) Delete(id uint) error { team, err := t.teamRepository.FindById(id) if err != nil || team.ID == 0 { - return errors.New("团队不存在") + return errors.New("team.not_found") } err = t.teamRepository.Delete(id) return err } -func (t *TeamService) Find(req request.TeamFindRequest) (teams []model.Team, total int64, err error) { - teams, total, err = t.teamRepository.Find(req) +func (t *TeamService) Find(req request.TeamFindRequest) ([]model.Team, int64, error) { + teams, total, err := t.teamRepository.Find(req) for index, team := range teams { team.InviteToken = "" teams[index] = team @@ -84,20 +94,10 @@ func (t *TeamService) Find(req request.TeamFindRequest) (teams []model.Team, tot return teams, total, err } -func (t *TeamService) FindById(id uint) (team model.Team, err error) { - teams, _, err := t.teamRepository.Find(request.TeamFindRequest{ - ID: id, - }) - if len(teams) > 0 { - team = teams[0] - } - return team, err -} - func (t *TeamService) GetInviteToken(req request.TeamGetInviteTokenRequest) (token string, err error) { team, err := t.teamRepository.FindById(req.ID) if err != nil || team.ID == 0 { - return "", errors.New("团队不存在") + return "", errors.New("team.not_found") } return team.InviteToken, err } @@ -105,7 +105,7 @@ func (t *TeamService) GetInviteToken(req request.TeamGetInviteTokenRequest) (tok func (t *TeamService) UpdateInviteToken(req request.TeamUpdateInviteTokenRequest) (token string, err error) { team, err := t.teamRepository.FindById(req.ID) if err != nil || team.ID == 0 { - return "", errors.New("团队不存在") + return "", errors.New("team.not_found") } uid := uuid.NewString() token = uid[:8] + uid[9:13] + uid[14:18] + uid[19:23] + uid[24:] diff --git a/internal/service/user.go b/internal/service/user.go index b84150fd..95562173 100644 --- a/internal/service/user.go +++ b/internal/service/user.go @@ -15,14 +15,26 @@ import ( ) type IUserService interface { - Create(req request.UserCreateRequest) (err error) - Register(req request.UserRegisterRequest) (err error) - Update(req request.UserUpdateRequest) (err error) + // Create will create a new user with the given request. + Create(req request.UserCreateRequest) error + + // Update will update the user with the given request. + Update(req request.UserUpdateRequest) error + + // Delete will delete the user with the given id. Delete(id uint) error - VerifyPasswordByUsername(username string, password string) bool - GetJwtTokenByID(user model.User) (tokenString string, err error) - GetIDByJwtToken(token string) (id uint, err error) - Find(req request.UserFindRequest) (users []model.User, total int64, err error) + + // Find will return the users, total count and error. + Find(req request.UserFindRequest) ([]model.User, int64, error) + + // Register will create a new user with the given request, but the default group is user. + Register(req request.UserRegisterRequest) error + + // Login will verify the user login request and return the user and jwt token. + Login(req request.UserLoginRequest) (model.User, string, error) + + // Logout will log out the user with the given token. + Logout(token string) (uint, error) } type UserService struct { @@ -48,7 +60,7 @@ func (t *UserService) GetJwtTokenByID(user model.User) (tokenString string, err return pgsToken.SignedString(jwtSecretKey) } -func (t *UserService) GetIDByJwtToken(token string) (id uint, err error) { +func (t *UserService) Logout(token string) (uint, error) { pgsToken, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) { return []byte(config.JwtSecretKey()), nil }) @@ -62,7 +74,7 @@ func (t *UserService) GetIDByJwtToken(token string) (id uint, err error) { } } -func (t *UserService) Create(req request.UserCreateRequest) (err error) { +func (t *UserService) Create(req request.UserCreateRequest) error { hashedPassword, _ := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost) userModel := model.User{ Username: strings.ToLower(req.Username), @@ -71,11 +83,12 @@ func (t *UserService) Create(req request.UserCreateRequest) (err error) { Group: req.Group, Password: string(hashedPassword), } - err = t.userRepository.Create(userModel) + err := t.userRepository.Create(userModel) return err } -func (t *UserService) Register(req request.UserRegisterRequest) (err error) { +func (t *UserService) Register(req request.UserRegisterRequest) error { + var err error hashedPassword, _ := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost) success := true if config.PltCfg().User.Register.Captcha.Enabled { @@ -95,20 +108,20 @@ func (t *UserService) Register(req request.UserRegisterRequest) (err error) { return err } -func (t *UserService) Update(req request.UserUpdateRequest) (err error) { - userModel := model.User{} - _ = mapstructure.Decode(req, &userModel) +func (t *UserService) Update(req request.UserUpdateRequest) error { + user := model.User{} + _ = mapstructure.Decode(req, &user) if req.Password != "" { hashedPassword, _ := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost) - userModel.Password = string(hashedPassword) + user.Password = string(hashedPassword) } if req.Username != "" { - userModel.Username = strings.ToLower(req.Username) + user.Username = strings.ToLower(req.Username) } if req.Email != "" { - userModel.Email = strings.ToLower(req.Email) + user.Email = strings.ToLower(req.Email) } - err = t.userRepository.Update(userModel) + err := t.userRepository.Update(user) return err } @@ -117,28 +130,23 @@ func (t *UserService) Delete(id uint) error { return err } -func (t *UserService) Find(req request.UserFindRequest) (users []model.User, total int64, err error) { - users, total, err = t.userRepository.Find(req) +func (t *UserService) Find(req request.UserFindRequest) ([]model.User, int64, error) { + users, total, err := t.userRepository.Find(req) for index := range users { users[index].Simplify() } return users, total, err } -func (t *UserService) VerifyPasswordById(id uint, password string) bool { - user, err := t.userRepository.FindById(id) - err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)) +func (t *UserService) Login(req request.UserLoginRequest) (model.User, string, error) { + user, err := t.userRepository.FindByUsername(strings.ToLower(req.Username)) if err != nil { - return false + return user, "", errors.New("user.not_found") } - return true -} - -func (t *UserService) VerifyPasswordByUsername(username string, password string) bool { - user, err := t.userRepository.FindByUsername(strings.ToLower(username)) - err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)) + err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.Password)) if err != nil { - return false + return user, "", errors.New("user.login.password_incorrect") } - return true + token, err := t.GetJwtTokenByID(user) + return user, token, err } diff --git a/internal/utils/const.go b/internal/utils/const.go index 8da27a26..42f627a8 100644 --- a/internal/utils/const.go +++ b/internal/utils/const.go @@ -14,3 +14,8 @@ const ( CapturesPath = "./captures" FrontendPath = "./dist" ) + +var ( + True = true + False = false +) diff --git a/internal/utils/convertor/convertor.go b/internal/utils/convertor/convertor.go index ea3e970f..a01764a8 100644 --- a/internal/utils/convertor/convertor.go +++ b/internal/utils/convertor/convertor.go @@ -5,16 +5,6 @@ import ( "strconv" ) -func TrueP() *bool { - i := true - return &i -} - -func FalseP() *bool { - i := false - return &i -} - func ToInt64D(v string, d int64) int64 { result, err := convertor.ToInt(v) if err != nil { diff --git a/web/src/api/challenge.ts b/web/src/api/challenge.ts index 8288269f..320f7f2c 100644 --- a/web/src/api/challenge.ts +++ b/web/src/api/challenge.ts @@ -48,10 +48,6 @@ export function useChallengeApi() { ); }; - const getChallengeAttachment = (id: number) => { - return auth.get(`/challenges/${id}/attachment`); - }; - const saveChallengeAttachment = ( id: number, file: File, @@ -74,7 +70,6 @@ export function useChallengeApi() { updateChallengeFlag, createChallengeFlag, deleteChallengeFlag, - getChallengeAttachment, saveChallengeAttachment, deleteChallengeAttachment, }; diff --git a/web/src/api/media.ts b/web/src/api/media.ts deleted file mode 100644 index 49fafe13..00000000 --- a/web/src/api/media.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { useAuth } from "@/utils/axios"; - -export function useMediaApi() { - const auth = useAuth(); - - const getChallengeAttachmentInfoByChallengeID = (id: number) => { - return auth.get(`/media/challenges/attachments/${id}/info`); - }; - - const getChallengeAttachmentByChallengeID = (id: number) => { - return auth.get(`/media/challenges/attachments/${id}`); - }; - - const setChallengeAttachmentByChallengeID = (id: number, data: any) => { - return auth.post(`/media/challenges/attachments/${id}`, data); - }; - - const deleteChallengeAttachmentByChallengeID = (id: number) => { - return auth.delete(`/media/challenges/attachments/${id}`); - }; - - return { - getChallengeAttachmentInfoByChallengeID, - getChallengeAttachmentByChallengeID, - setChallengeAttachmentByChallengeID, - deleteChallengeAttachmentByChallengeID, - }; -} diff --git a/web/src/pages/login.tsx b/web/src/pages/login.tsx index 78f7c5e0..c8f3cafa 100644 --- a/web/src/pages/login.tsx +++ b/web/src/pages/login.tsx @@ -65,19 +65,10 @@ export default function Page() { navigate("/"); }) .catch((err) => { - switch (err?.response?.status) { - case 400: - showErrNotification({ - message: "用户名或密码错误", - }); - break; - default: - showErrNotification({ - title: "发生了错误", - message: `登录失败 ${err}`, - }); - break; - } + showErrNotification({ + title: "发生了错误", + message: `登录失败 ${err.response?.data?.msg}`, + }); }) .finally(() => { setLoginLoading(false); diff --git a/web/src/utils/axios.ts b/web/src/utils/axios.ts index 34be0db5..aa2d5209 100644 --- a/web/src/utils/axios.ts +++ b/web/src/utils/axios.ts @@ -8,6 +8,9 @@ export const useApi = () => { return useMemo(() => { const api = axios.create({ baseURL: import.meta.env.VITE_BASE_API as string, + headers: { + "Accept-Language": "zh-Hans", + }, }); return api; }, []); @@ -21,11 +24,10 @@ export const useAuth = () => { return useMemo(() => { const auth = axios.create({ baseURL: import.meta.env.VITE_BASE_API as string, - headers: pgsToken - ? { - Authorization: `${pgsToken}`, - } - : {}, + headers: { + Authorization: pgsToken ? `${pgsToken}` : undefined, + "Accept-Language": "zh-Hans", + }, }); auth.interceptors.response.use(