diff --git a/models/user/badge.go b/models/user/badge.go index 3ff3530a369a5..1497981d9916c 100644 --- a/models/user/badge.go +++ b/models/user/badge.go @@ -6,8 +6,12 @@ package user import ( "context" "fmt" + "strings" "code.gitea.io/gitea/models/db" + + "xorm.io/builder" + "xorm.io/xorm" ) // Badge represents a user badge @@ -42,13 +46,27 @@ func GetUserBadges(ctx context.Context, u *User) ([]*Badge, int64, error) { return badges, count, err } +// GetBadgeUsers returns the users that have a specific badge. +func GetBadgeUsers(ctx context.Context, b *Badge) ([]*User, int64, error) { + sess := db.GetEngine(ctx). + Select("`user`.*"). + Join("INNER", "user_badge", "`user_badge`.user_id=user.id"). + Join("INNER", "badge", "`user_badge`.badge_id=badge.id"). + Where("badge.slug=?", b.Slug) + users := make([]*User, 0, 8) + count, err := sess.FindAndCount(&users) + return users, count, err +} + // CreateBadge creates a new badge. func CreateBadge(ctx context.Context, badge *Badge) error { + // this will fail if the badge already exists due to the UNIQUE constraint _, err := db.GetEngine(ctx).Insert(badge) + return err } -// GetBadge returns a badge +// GetBadge returns a specific badge func GetBadge(ctx context.Context, slug string) (*Badge, error) { badge := new(Badge) has, err := db.GetEngine(ctx).Where("slug=?", slug).Get(badge) @@ -60,7 +78,7 @@ func GetBadge(ctx context.Context, slug string) (*Badge, error) { // UpdateBadge updates a badge based on its slug. func UpdateBadge(ctx context.Context, badge *Badge) error { - _, err := db.GetEngine(ctx).Where("slug=?", badge.Slug).Update(badge) + _, err := db.GetEngine(ctx).Where("slug=?", badge.Slug).Cols("description", "image_url").Update(badge) return err } @@ -84,7 +102,7 @@ func AddUserBadges(ctx context.Context, u *User, badges []*Badge) error { if err != nil { return err } else if !has { - return fmt.Errorf("badge with slug %s doesn't exist", badge.Slug) + return ErrBadgeNotExist{Slug: badge.Slug} } if err := db.Insert(ctx, &UserBadge{ BadgeID: badge.ID, @@ -102,13 +120,18 @@ func RemoveUserBadge(ctx context.Context, u *User, badge *Badge) error { return RemoveUserBadges(ctx, u, []*Badge{badge}) } -// RemoveUserBadges removes badges from a user. +// RemoveUserBadges removes specific badges from a user. func RemoveUserBadges(ctx context.Context, u *User, badges []*Badge) error { return db.WithTx(ctx, func(ctx context.Context) error { for _, badge := range badges { + subQuery := builder. + Select("id"). + From("badge"). + Where(builder.Eq{"slug": badge.Slug}) + if _, err := db.GetEngine(ctx). - Join("INNER", "badge", "badge.id = `user_badge`.badge_id"). - Where("`user_badge`.user_id=? AND `badge`.slug=?", u.ID, badge.Slug). + Where("`user_badge`.user_id=?", u.ID). + And(builder.In("badge_id", subQuery)). Delete(&UserBadge{}); err != nil { return err } @@ -122,3 +145,91 @@ func RemoveAllUserBadges(ctx context.Context, u *User) error { _, err := db.GetEngine(ctx).Where("user_id=?", u.ID).Delete(&UserBadge{}) return err } + +// SearchBadgeOptions represents the options when fdin badges +type SearchBadgeOptions struct { + db.ListOptions + + Keyword string + Slug string + ID int64 + OrderBy db.SearchOrderBy + Actor *User // The user doing the search + + ExtraParamStrings map[string]string +} + +func (opts *SearchBadgeOptions) ToConds() builder.Cond { + cond := builder.NewCond() + + if opts.Keyword != "" { + cond = cond.And(builder.Like{"badge.slug", opts.Keyword}) + } + + return cond +} + +func (opts *SearchBadgeOptions) ToOrders() string { + orderBy := "badge.slug" + return orderBy +} + +func (opts *SearchBadgeOptions) ToJoins() []db.JoinFunc { + return []db.JoinFunc{ + func(e db.Engine) error { + e.Join("INNER", "badge", "`user_badge`.badge_id=badge.id") + return nil + }, + } +} + +func SearchBadges(ctx context.Context, opts *SearchBadgeOptions) (badges []*Badge, _ int64, _ error) { + sessCount := opts.toSearchQueryBase(ctx) + count, err := sessCount.Count(new(Badge)) + if err != nil { + return nil, 0, fmt.Errorf("count: %w", err) + } + sessCount.Close() + + if len(opts.OrderBy) == 0 { + opts.OrderBy = db.SearchOrderByID + } + + sessQuery := opts.toSearchQueryBase(ctx).OrderBy(opts.OrderBy.String()) + defer sessQuery.Close() + if opts.Page != 0 { + sessQuery = db.SetSessionPagination(sessQuery, opts) + } + + // the sql may contain JOIN, so we must only select Badge related columns + sessQuery = sessQuery.Select("`badge`.*") + badges = make([]*Badge, 0, opts.PageSize) + return badges, count, sessQuery.Find(&badges) +} + +func (opts *SearchBadgeOptions) toSearchQueryBase(ctx context.Context) *xorm.Session { + var cond builder.Cond + cond = builder.Neq{"id": -1} + + if len(opts.Keyword) > 0 { + lowerKeyword := strings.ToLower(opts.Keyword) + keywordCond := builder.Or( + builder.Like{"slug", lowerKeyword}, + builder.Like{"description", lowerKeyword}, + builder.Like{"id", lowerKeyword}, + ) + cond = cond.And(keywordCond) + } + + if opts.ID > 0 { + cond = cond.And(builder.Eq{"id": opts.ID}) + } + + if len(opts.Slug) > 0 { + cond = cond.And(builder.Eq{"slug": opts.Slug}) + } + + e := db.GetEngine(ctx) + + return e.Where(cond) +} diff --git a/models/user/error.go b/models/user/error.go index cbf19998d10ab..88986ee93cf7c 100644 --- a/models/user/error.go +++ b/models/user/error.go @@ -107,3 +107,43 @@ func IsErrUserIsNotLocal(err error) bool { _, ok := err.(ErrUserIsNotLocal) return ok } + +// ErrBadgeAlreadyExist represents a "badge already exists" error. +type ErrBadgeAlreadyExist struct { + Slug string +} + +// IsErrBadgeAlreadyExist checks if an error is a ErrBadgeAlreadyExist. +func IsErrBadgeAlreadyExist(err error) bool { + _, ok := err.(ErrBadgeAlreadyExist) + return ok +} + +func (err ErrBadgeAlreadyExist) Error() string { + return fmt.Sprintf("badge already exists [slug: %s]", err.Slug) +} + +// Unwrap unwraps this error as a ErrExist error +func (err ErrBadgeAlreadyExist) Unwrap() error { + return util.ErrAlreadyExist +} + +// ErrBadgeNotExist represents a "BadgeNotExist" kind of error. +type ErrBadgeNotExist struct { + Slug string +} + +// IsErrBadgeNotExist checks if an error is a ErrBadgeNotExist. +func IsErrBadgeNotExist(err error) bool { + _, ok := err.(ErrBadgeNotExist) + return ok +} + +func (err ErrBadgeNotExist) Error() string { + return fmt.Sprintf("badge does not exist [slug: %s]", err.Slug) +} + +// Unwrap unwraps this error as a ErrNotExist error +func (err ErrBadgeNotExist) Unwrap() error { + return util.ErrNotExist +} diff --git a/modules/validation/binding.go b/modules/validation/binding.go index cb0a5063e509b..dadcdb1edb655 100644 --- a/modules/validation/binding.go +++ b/modules/validation/binding.go @@ -26,6 +26,8 @@ const ( ErrUsername = "UsernameError" // ErrInvalidGroupTeamMap is returned when a group team mapping is invalid ErrInvalidGroupTeamMap = "InvalidGroupTeamMap" + // ErrInvalidSlug is returned when a slug is invalid + ErrInvalidSlug = "InvalidSlug" ) // AddBindingRules adds additional binding rules @@ -38,6 +40,7 @@ func AddBindingRules() { addGlobOrRegexPatternRule() addUsernamePatternRule() addValidGroupTeamMapRule() + addSlugPatternRule() } func addGitRefNameBindingRule() { @@ -94,6 +97,22 @@ func addValidSiteURLBindingRule() { }) } +func addSlugPatternRule() { + binding.AddRule(&binding.Rule{ + IsMatch: func(rule string) bool { + return rule == "Slug" + }, + IsValid: func(errs binding.Errors, name string, val any) (bool, binding.Errors) { + str := fmt.Sprintf("%v", val) + if !IsValidSlug(str) { + errs.Add([]string{name}, ErrInvalidSlug, "invalid slug") + return false, errs + } + return true, errs + }, + }) +} + func addGlobPatternRule() { binding.AddRule(&binding.Rule{ IsMatch: func(rule string) bool { diff --git a/modules/validation/helpers.go b/modules/validation/helpers.go index f6e00f3887a43..1fba01b2a08f1 100644 --- a/modules/validation/helpers.go +++ b/modules/validation/helpers.go @@ -127,3 +127,7 @@ func IsValidUsername(name string) bool { // but it's easier to use positive and negative checks. return validUsernamePattern.MatchString(name) && !invalidUsernamePattern.MatchString(name) } + +func IsValidSlug(slug string) bool { + return IsValidUsername(slug) +} diff --git a/modules/web/middleware/binding.go b/modules/web/middleware/binding.go index 43e1bbc70e3b5..6a7582ed8f827 100644 --- a/modules/web/middleware/binding.go +++ b/modules/web/middleware/binding.go @@ -138,6 +138,8 @@ func Validate(errs binding.Errors, data map[string]any, f Form, l translation.Lo data["ErrorMsg"] = trName + l.TrString("form.username_error") case validation.ErrInvalidGroupTeamMap: data["ErrorMsg"] = trName + l.TrString("form.invalid_group_team_map_error", errs[0].Message) + case validation.ErrInvalidSlug: + data["ErrorMsg"] = l.TrString("form.invalid_slug_error") default: msg := errs[0].Classification if msg != "" && errs[0].Message != "" { diff --git a/options/locale/locale_en-US.ini b/options/locale/locale_en-US.ini index a02d939b79eda..aebba54ec0272 100644 --- a/options/locale/locale_en-US.ini +++ b/options/locale/locale_en-US.ini @@ -170,6 +170,7 @@ exact = Exact exact_tooltip = Include only results that match the exact search term repo_kind = Search repos... user_kind = Search users... +badge_kind = Search badges... org_kind = Search orgs... team_kind = Search teams... code_kind = Search code... @@ -548,6 +549,7 @@ PayloadUrl = Payload URL TeamName = Team name AuthName = Authorization name AdminEmail = Admin email +ImageURL = Image URL NewBranchName = New branch name CommitSummary = Commit summary @@ -577,12 +579,15 @@ unknown_error = Unknown error: captcha_incorrect = The CAPTCHA code is incorrect. password_not_match = The passwords do not match. lang_select_error = Select a language from the list. +invalid_image_url_error = `Please provide a valid image URL.` +invalid_slug_error = `Please provide a valid slug.` username_been_taken = The username is already taken. username_change_not_local_user = Non-local users are not allowed to change their username. change_username_disabled = Changing username is disabled. change_full_name_disabled = Changing full name is disabled. username_has_not_been_changed = Username has not been changed +slug_been_taken = The slug is already taken. repo_name_been_taken = The repository name is already used. repository_force_private = Force Private is enabled: private repositories cannot be made public. repository_files_already_exist = Files already exist for this repository. Contact the system administrator. @@ -2844,6 +2849,7 @@ dashboard = Dashboard self_check = Self Check identity_access = Identity & Access users = User Accounts +badges = Badges organizations = Organizations assets = Code Assets repositories = Repositories @@ -3023,6 +3029,30 @@ emails.delete_desc = Are you sure you want to delete this email address? emails.deletion_success = The email address has been deleted. emails.delete_primary_email_error = You can not delete the primary email. +badges.badges_manage_panel = Badge Management +badges.details = Badge Details +badges.new_badge = Create New Badge +badges.slug = Slug +badges.description = Description +badges.image_url = Image URL +badges.slug.must_fill = Slug must be filled. +badges.new_success = The badge "%s" has been created. +badges.update_success = The badge has been updated. +badges.deletion_success = The badge has been deleted. +badges.edit_badge = Edit Badge +badges.update_badge = Update Badge +badges.delete_badge = Delete Badge +badges.delete_badge_desc = Are you sure you want to permanently delete this badge? +badges.users_with_badge = Users with Badge (%s) +badges.add_user = Add User +badges.remove_user = Remove User +badges.delete_user_desc = Are you sure you want to remove this badge from the user? +badges.not_found = Badge not found! +badges.user_add_success = User has been added to the badge. +badges.user_remove_success = User has been removed from the badge. +badges.manage_users = Manage Users + + orgs.org_manage_panel = Organization Management orgs.name = Name orgs.teams = Teams diff --git a/routers/web/admin/badges.go b/routers/web/admin/badges.go new file mode 100644 index 0000000000000..4bcf20cf30311 --- /dev/null +++ b/routers/web/admin/badges.go @@ -0,0 +1,274 @@ +// Copyright 2024 The Gitea Authors. +// SPDX-License-Identifier: MIT + +package admin + +import ( + "fmt" + "net/http" + "net/url" + "strconv" + "strings" + + "code.gitea.io/gitea/models/db" + user_model "code.gitea.io/gitea/models/user" + "code.gitea.io/gitea/modules/base" + "code.gitea.io/gitea/modules/log" + "code.gitea.io/gitea/modules/setting" + "code.gitea.io/gitea/modules/web" + "code.gitea.io/gitea/routers/web/explore" + "code.gitea.io/gitea/services/context" + "code.gitea.io/gitea/services/forms" + user_service "code.gitea.io/gitea/services/user" +) + +const ( + tplBadges base.TplName = "admin/badge/list" + tplBadgeNew base.TplName = "admin/badge/new" + tplBadgeView base.TplName = "admin/badge/view" + tplBadgeEdit base.TplName = "admin/badge/edit" + tplBadgeUsers base.TplName = "admin/badge/users" +) + +// BadgeSearchDefaultAdminSort is the default sort type for admin view +const BadgeSearchDefaultAdminSort = "oldest" + +// Badges show all the badges +func Badges(ctx *context.Context) { + ctx.Data["Title"] = ctx.Tr("admin.badges") + ctx.Data["PageIsAdminBadges"] = true + + sortType := ctx.FormString("sort") + if sortType == "" { + sortType = BadgeSearchDefaultAdminSort + ctx.SetFormString("sort", sortType) + } + ctx.PageData["adminBadgeListSearchForm"] = map[string]any{ + "SortType": sortType, + } + + explore.RenderBadgeSearch(ctx, &user_model.SearchBadgeOptions{ + Actor: ctx.Doer, + ListOptions: db.ListOptions{ + PageSize: setting.UI.Admin.UserPagingNum, + }, + }, tplBadges) +} + +// NewBadge render adding a new badge +func NewBadge(ctx *context.Context) { + ctx.Data["Title"] = ctx.Tr("admin.badges.new_badge") + ctx.Data["PageIsAdminBadges"] = true + + ctx.HTML(http.StatusOK, tplBadgeNew) +} + +// NewBadgePost response for adding a new badge +func NewBadgePost(ctx *context.Context) { + form := web.GetForm(ctx).(*forms.AdminCreateBadgeForm) + ctx.Data["Title"] = ctx.Tr("admin.badges.new_badge") + ctx.Data["PageIsAdminBadges"] = true + + if ctx.HasError() { + ctx.HTML(http.StatusOK, tplBadgeNew) + return + } + + b := &user_model.Badge{ + Slug: form.Slug, + Description: form.Description, + ImageURL: form.ImageURL, + } + + if len(form.Slug) < 1 { + ctx.Data["Err_Slug"] = true + ctx.RenderWithErr(ctx.Tr("admin.badges.must_fill"), tplBadgeNew, &form) + return + } + + if err := user_model.CreateBadge(ctx, b); err != nil { + switch { + default: + ctx.ServerError("CreateBadge", err) + } + return + } + + log.Trace("Badge created by admin (%s): %s", ctx.Doer.Name, b.Slug) + + ctx.Flash.Success(ctx.Tr("admin.badges.new_success", b.Slug)) + ctx.Redirect(setting.AppSubURL + "/admin/badges/" + strconv.FormatInt(b.ID, 10)) +} + +func prepareBadgeInfo(ctx *context.Context) *user_model.Badge { + b, err := user_model.GetBadge(ctx, ctx.PathParam(":badge_slug")) + if err != nil { + if user_model.IsErrBadgeNotExist(err) { + ctx.Redirect(setting.AppSubURL + "/admin/badges") + } else { + ctx.ServerError("GetBadge", err) + } + return nil + } + ctx.Data["Badge"] = b + + users, count, err := user_model.GetBadgeUsers(ctx, b) + if err != nil { + if user_model.IsErrUserNotExist(err) { + ctx.Redirect(setting.AppSubURL + "/admin/badges") + } else { + ctx.ServerError("GetBadgeUsers", err) + } + return nil + } + ctx.Data["Users"] = users + ctx.Data["UsersTotal"] = int(count) + + return b +} + +func ViewBadge(ctx *context.Context) { + ctx.Data["Title"] = ctx.Tr("admin.badges.details") + ctx.Data["PageIsAdminBadges"] = true + + prepareBadgeInfo(ctx) + if ctx.Written() { + return + } + + ctx.HTML(http.StatusOK, tplBadgeView) +} + +// EditBadge show editing badge page +func EditBadge(ctx *context.Context) { + ctx.Data["Title"] = ctx.Tr("admin.badges.edit_badges") + ctx.Data["PageIsAdminBadges"] = true + prepareBadgeInfo(ctx) + if ctx.Written() { + return + } + + ctx.HTML(http.StatusOK, tplBadgeEdit) +} + +// EditBadgePost response for editing badge +func EditBadgePost(ctx *context.Context) { + ctx.Data["Title"] = ctx.Tr("admin.badges.edit_badges") + ctx.Data["PageIsAdminBadges"] = true + b := prepareBadgeInfo(ctx) + if ctx.Written() { + return + } + + form := web.GetForm(ctx).(*forms.AdminCreateBadgeForm) + if ctx.HasError() { + ctx.HTML(http.StatusOK, tplBadgeEdit) + return + } + + if form.Slug != "" { + if err := user_service.UpdateBadge(ctx, ctx.Data["Badge"].(*user_model.Badge)); err != nil { + switch { + default: + ctx.ServerError("UpdateBadge", err) + } + return + } + } + + b.ImageURL = form.ImageURL + b.Description = form.Description + + if err := user_model.UpdateBadge(ctx, ctx.Data["Badge"].(*user_model.Badge)); err != nil { + ctx.ServerError("UpdateBadge", err) + return + } + + log.Trace("Badge updated by admin (%s): %s", ctx.Doer.Name, b.Slug) + + ctx.Flash.Success(ctx.Tr("admin.badges.update_success")) + ctx.Redirect(setting.AppSubURL + "/admin/badges/" + url.PathEscape(ctx.PathParam(":badge_slug"))) +} + +// DeleteBadge response for deleting a badge +func DeleteBadge(ctx *context.Context) { + b, err := user_model.GetBadge(ctx, ctx.PathParam(":badge_slug")) + if err != nil { + ctx.ServerError("GetBadge", err) + return + } + + if err = user_service.DeleteBadge(ctx, b); err != nil { + ctx.ServerError("DeleteBadge", err) + return + } + + log.Trace("Badge deleted by admin (%s): %s", ctx.Doer.Name, b.Slug) + + ctx.Flash.Success(ctx.Tr("admin.badges.deletion_success")) + ctx.Redirect(setting.AppSubURL + "/admin/badges") +} + +func BadgeUsers(ctx *context.Context) { + ctx.Data["Title"] = ctx.Tr("admin.badges.users_with_badge", ctx.PathParam(":badge_slug")) + ctx.Data["PageIsAdminBadges"] = true + + users, _, err := user_model.GetBadgeUsers(ctx, &user_model.Badge{Slug: ctx.PathParam(":badge_slug")}) + if err != nil { + ctx.ServerError("GetBadgeUsers", err) + return + } + + ctx.Data["Users"] = users + + ctx.HTML(http.StatusOK, tplBadgeUsers) +} + +// BadgeUsersPost response for actions for user badges +func BadgeUsersPost(ctx *context.Context) { + name := strings.ToLower(ctx.FormString("user")) + + u, err := user_model.GetUserByName(ctx, name) + if err != nil { + if user_model.IsErrUserNotExist(err) { + ctx.Flash.Error(ctx.Tr("form.user_not_exist")) + ctx.Redirect(setting.AppSubURL + ctx.Req.URL.EscapedPath()) + } else { + ctx.ServerError("GetUserByName", err) + } + return + } + + if err = user_model.AddUserBadge(ctx, u, &user_model.Badge{Slug: ctx.PathParam(":badge_slug")}); err != nil { + if user_model.IsErrBadgeNotExist(err) { + ctx.Flash.Error(ctx.Tr("admin.badges.not_found")) + } else { + ctx.ServerError("AddUserBadge", err) + } + return + } + + ctx.Flash.Success(ctx.Tr("admin.badges.user_add_success")) + ctx.Redirect(setting.AppSubURL + ctx.Req.URL.EscapedPath()) +} + +// DeleteBadgeUser delete a badge from a user +func DeleteBadgeUser(ctx *context.Context) { + user, err := user_model.GetUserByID(ctx, ctx.FormInt64("id")) + if err != nil { + if user_model.IsErrUserNotExist(err) { + ctx.Flash.Error(ctx.Tr("form.user_not_exist")) + } else { + ctx.ServerError("GetUserByName", err) + return + } + } + if err := user_model.RemoveUserBadge(ctx, user, &user_model.Badge{Slug: ctx.PathParam(":badge_slug")}); err == nil { + ctx.Flash.Success(ctx.Tr("admin.badges.user_remove_success")) + } else { + ctx.Flash.Error("DeleteUser: " + err.Error()) + return + } + + ctx.JSONRedirect(fmt.Sprintf("%s/admin/badges/%s/users", setting.AppSubURL, ctx.PathParam(":badge_slug"))) +} diff --git a/routers/web/explore/badge.go b/routers/web/explore/badge.go new file mode 100644 index 0000000000000..cc6bd2dc6399d --- /dev/null +++ b/routers/web/explore/badge.go @@ -0,0 +1,78 @@ +// Copyright 2024 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package explore + +import ( + "net/http" + + "code.gitea.io/gitea/models/db" + user_model "code.gitea.io/gitea/models/user" + "code.gitea.io/gitea/modules/base" + "code.gitea.io/gitea/modules/setting" + "code.gitea.io/gitea/services/context" +) + +func RenderBadgeSearch(ctx *context.Context, opts *user_model.SearchBadgeOptions, tplName base.TplName) { + // Sitemap index for sitemap paths + opts.Page = int(ctx.PathParamInt64("idx")) + if opts.Page <= 1 { + opts.Page = ctx.FormInt("page") + } + if opts.Page <= 1 { + opts.Page = 1 + } + + var ( + badges []*user_model.Badge + count int64 + err error + orderBy db.SearchOrderBy + ) + + // we can not set orderBy to `models.SearchOrderByXxx`, because there may be a JOIN in the statement, different tables may have the same name columns + + sortOrder := ctx.FormString("sort") + if sortOrder == "" { + sortOrder = setting.UI.ExploreDefaultSort + } + ctx.Data["SortType"] = sortOrder + + switch sortOrder { + case "newest": + orderBy = "`badge`.id DESC" + case "oldest": + orderBy = "`badge`.id ASC" + case "reversealphabetically": + orderBy = "`badge`.slug DESC" + case "alphabetically": + orderBy = "`badge`.slug ASC" + default: + // in case the sortType is not valid, we set it to recent update + ctx.Data["SortType"] = "oldest" + orderBy = "`badge`.id ASC" + } + + opts.Keyword = ctx.FormTrim("q") + opts.OrderBy = orderBy + if len(opts.Keyword) == 0 || isKeywordValid(opts.Keyword) { + badges, count, err = user_model.SearchBadges(ctx, opts) + if err != nil { + ctx.ServerError("SearchBadges", err) + return + } + } + + ctx.Data["Keyword"] = opts.Keyword + ctx.Data["Total"] = count + ctx.Data["Badges"] = badges + + pager := context.NewPagination(int(count), opts.PageSize, opts.Page, 5) + pager.SetDefaultParams(ctx) + for paramKey, paramVal := range opts.ExtraParamStrings { + pager.AddParamString(paramKey, paramVal) + } + ctx.Data["Page"] = pager + + ctx.HTML(http.StatusOK, tplName) +} diff --git a/routers/web/web.go b/routers/web/web.go index 80399ec499c50..5b5a055f836dd 100644 --- a/routers/web/web.go +++ b/routers/web/web.go @@ -723,6 +723,16 @@ func registerRoutes(m *web.Router) { m.Post("/{userid}/avatar/delete", admin.DeleteAvatar) }) + m.Group("/badges", func() { + m.Get("", admin.Badges) + m.Combo("/new").Get(admin.NewBadge).Post(web.Bind(forms.AdminCreateBadgeForm{}), admin.NewBadgePost) + m.Get("/{badge_slug}", admin.ViewBadge) + m.Combo("/{badge_slug}/edit").Get(admin.EditBadge).Post(web.Bind(forms.AdminCreateBadgeForm{}), admin.EditBadgePost) + m.Post("/{badge_slug}/delete", admin.DeleteBadge) + m.Combo("/{badge_slug}/users").Get(admin.BadgeUsers).Post(admin.BadgeUsersPost) + m.Post("/{badge_slug}/users/delete", admin.DeleteBadgeUser) + }) + m.Group("/emails", func() { m.Get("", admin.Emails) m.Post("/activate", admin.ActivateEmail) diff --git a/services/forms/admin.go b/services/forms/admin.go index 81276f8f46f9c..57ec92ed412a5 100644 --- a/services/forms/admin.go +++ b/services/forms/admin.go @@ -25,6 +25,19 @@ type AdminCreateUserForm struct { Visibility structs.VisibleType } +// AdminCreateBadgeForm form for admin to create badge +type AdminCreateBadgeForm struct { + Slug string `binding:"Required;Slug"` + Description string + ImageURL string `binding:"ValidImageUrl"` +} + +// Validate validates form fields +func (f *AdminCreateBadgeForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { + ctx := context.GetValidateContext(req) + return middleware.Validate(errs, ctx.Data, f, ctx.Locale) +} + // Validate validates form fields func (f *AdminCreateUserForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { ctx := context.GetValidateContext(req) diff --git a/services/user/badge.go b/services/user/badge.go new file mode 100644 index 0000000000000..d4c6fe88efabd --- /dev/null +++ b/services/user/badge.go @@ -0,0 +1,46 @@ +// Copyright 2024 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package user + +import ( + "context" + "fmt" + + "code.gitea.io/gitea/models/db" + user_model "code.gitea.io/gitea/models/user" +) + +// UpdateBadgeDescription changes the description and/or image of a badge +func UpdateBadge(ctx context.Context, b *user_model.Badge) error { + ctx, committer, err := db.TxContext(ctx) + if err != nil { + return err + } + defer committer.Close() + + if err := user_model.UpdateBadge(ctx, b); err != nil { + return err + } + return committer.Commit() +} + +// DeleteBadge remove record of badge in the database +func DeleteBadge(ctx context.Context, b *user_model.Badge) error { + ctx, committer, err := db.TxContext(ctx) + if err != nil { + return err + } + defer committer.Close() + + if err := user_model.DeleteBadge(ctx, b); err != nil { + return fmt.Errorf("DeleteBadge: %w", err) + } + + if err := committer.Commit(); err != nil { + return err + } + _ = committer.Close() + + return nil +} diff --git a/templates/admin/badge/edit.tmpl b/templates/admin/badge/edit.tmpl new file mode 100644 index 0000000000000..2c6e197a7a18d --- /dev/null +++ b/templates/admin/badge/edit.tmpl @@ -0,0 +1,48 @@ +{{template "admin/layout_head" (dict "ctxData" . "pageClass" "admin edit user")}} +
+

+ {{ctx.Locale.Tr "admin.badges.edit_badge"}} +

+
+
+ {{template "base/disable_form_autofill"}} + {{.CsrfTokenHtml}} + +
+ + +
+
+ + +
+
+ + +
+ +
+ +
+ + +
+
+
+
+ + + +{{template "admin/layout_footer" .}} diff --git a/templates/admin/badge/list.tmpl b/templates/admin/badge/list.tmpl new file mode 100644 index 0000000000000..0f4db0fc9ed91 --- /dev/null +++ b/templates/admin/badge/list.tmpl @@ -0,0 +1,67 @@ +{{template "admin/layout_head" (dict "ctxData" . "pageClass" "admin user")}} +
+

+ {{ctx.Locale.Tr "admin.badges.badges_manage_panel"}} ({{ctx.Locale.Tr "admin.total" .Total}}) + +

+
+
+ + + + + {{template "shared/search/combo" dict "Value" .Keyword "Placeholder" (ctx.Locale.Tr "search.badge_kind")}} +
+
+
+ + + + + + + + + + + {{range .Badges}} + + + + + + + {{end}} + +
ID{{SortArrow "oldest" "newest" .SortType false}} + {{ctx.Locale.Tr "admin.badges.slug"}} + {{SortArrow "alphabetically" "reversealphabeically" $.SortType true}} + {{ctx.Locale.Tr "admin.badges.description"}}
{{.ID}} + {{.Slug}} + {{.Description}} + +
+
+ + {{template "base/paginate" .}} +
+{{template "admin/layout_footer" .}} diff --git a/templates/admin/badge/new.tmpl b/templates/admin/badge/new.tmpl new file mode 100644 index 0000000000000..9dc756c7bb047 --- /dev/null +++ b/templates/admin/badge/new.tmpl @@ -0,0 +1,30 @@ +{{template "admin/layout_head" (dict "ctxData" . "pageClass" "admin new user")}} +
+

+ {{ctx.Locale.Tr "admin.badges.new_badge"}} +

+
+
+ {{template "base/disable_form_autofill"}} + {{.CsrfTokenHtml}} + +
+ + +
+
+ + +
+
+ + +
+ +
+ +
+
+
+
+{{template "admin/layout_footer" .}} diff --git a/templates/admin/badge/users.tmpl b/templates/admin/badge/users.tmpl new file mode 100644 index 0000000000000..41088170cc7c8 --- /dev/null +++ b/templates/admin/badge/users.tmpl @@ -0,0 +1,54 @@ +{{template "admin/layout_head" (dict "ctxData" . "pageClass" "admin user")}} +
+

+ {{.Title}} +

+ {{if .Users}} +
+
+ {{range .Users}} +
+ +
+
+ {{template "shared/user/name" .}} +
+
+
+ +
+
+ {{end}} +
+
+ {{end}} +
+
+ {{.CsrfTokenHtml}} + + +
+
+
+ + + +{{template "admin/layout_footer" .}} diff --git a/templates/admin/badge/view.tmpl b/templates/admin/badge/view.tmpl new file mode 100644 index 0000000000000..1f4a3e11c4197 --- /dev/null +++ b/templates/admin/badge/view.tmpl @@ -0,0 +1,44 @@ +{{template "admin/layout_head" (dict "ctxData" . "pageClass" "admin view user")}} + +
+
+
+

+ {{.Title}} + +

+
+
+
+ {{if .Image}} +
+ {{.Badge.Description}} +
+ {{end}} +
+
+ {{.Badge.Slug}} +
+
+ {{.Badge.Description}} +
+
+
+
+
+
+
+

+ {{ctx.Locale.Tr "explore.users"}} ({{.UsersTotal}}) + +

+
+ {{template "explore/user_list" .}} +
+
+ +{{template "admin/layout_footer" .}} diff --git a/templates/admin/navbar.tmpl b/templates/admin/navbar.tmpl index 4116357d1d235..2d8d20691b06f 100644 --- a/templates/admin/navbar.tmpl +++ b/templates/admin/navbar.tmpl @@ -13,7 +13,7 @@ -
+
{{ctx.Locale.Tr "admin.identity_access"}}