Skip to content

Commit

Permalink
Merge remote-tracking branch 'giteaofficial/main'
Browse files Browse the repository at this point in the history
* giteaofficial/main:
  Make GetRepositoryByName more safer (go-gitea#31712)
  [skip ci] Updated licenses and gitignores
  Run `go-install` in `deps-tools` in parallel (go-gitea#31711)
  Hide the "Details" link of commit status when the user cannot access actions (go-gitea#30156)
  Enable `no-jquery/no-parse-html-literal` and fix violation (go-gitea#31684)
  [skip ci] Updated translations via Crowdin
  OIDC: case-insensitive comparison for auth scheme `Basic` (go-gitea#31706)
  Support `pull_request_target` event for commit status (go-gitea#31703)
  Add types to fetch,toast,bootstrap,svg (go-gitea#31627)
  Run `detectWebAuthnSupport` only if necessary (go-gitea#31691)
  add `username` to OIDC introspection response (go-gitea#31688)
  Add return type to GetRawFileOrLFS and GetRawFile (go-gitea#31680)
  Support delete user email in admin panel (go-gitea#31690)
  Use GetDisplayName() instead of DisplayName() to generate rss feeds (go-gitea#31687)
  • Loading branch information
zjjhot committed Jul 29, 2024
2 parents b8fd763 + d109923 commit 5481812
Show file tree
Hide file tree
Showing 38 changed files with 358 additions and 79 deletions.
2 changes: 1 addition & 1 deletion .eslintrc.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -568,7 +568,7 @@ rules:
no-jquery/no-param: [2]
no-jquery/no-parent: [0]
no-jquery/no-parents: [2]
no-jquery/no-parse-html-literal: [0]
no-jquery/no-parse-html-literal: [2]
no-jquery/no-parse-html: [2]
no-jquery/no-parse-json: [2]
no-jquery/no-parse-xml: [2]
Expand Down
25 changes: 13 additions & 12 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -858,18 +858,19 @@ deps-backend:

.PHONY: deps-tools
deps-tools:
$(GO) install $(AIR_PACKAGE)
$(GO) install $(EDITORCONFIG_CHECKER_PACKAGE)
$(GO) install $(GOFUMPT_PACKAGE)
$(GO) install $(GOLANGCI_LINT_PACKAGE)
$(GO) install $(GXZ_PACKAGE)
$(GO) install $(MISSPELL_PACKAGE)
$(GO) install $(SWAGGER_PACKAGE)
$(GO) install $(XGO_PACKAGE)
$(GO) install $(GO_LICENSES_PACKAGE)
$(GO) install $(GOVULNCHECK_PACKAGE)
$(GO) install $(ACTIONLINT_PACKAGE)
$(GO) install $(GOPLS_PACKAGE)
$(GO) install $(AIR_PACKAGE) & \
$(GO) install $(EDITORCONFIG_CHECKER_PACKAGE) & \
$(GO) install $(GOFUMPT_PACKAGE) & \
$(GO) install $(GOLANGCI_LINT_PACKAGE) & \
$(GO) install $(GXZ_PACKAGE) & \
$(GO) install $(MISSPELL_PACKAGE) & \
$(GO) install $(SWAGGER_PACKAGE) & \
$(GO) install $(XGO_PACKAGE) & \
$(GO) install $(GO_LICENSES_PACKAGE) & \
$(GO) install $(GOVULNCHECK_PACKAGE) & \
$(GO) install $(ACTIONLINT_PACKAGE) & \
$(GO) install $(GOPLS_PACKAGE) & \
wait

node_modules: package-lock.json
npm install --no-save
Expand Down
40 changes: 39 additions & 1 deletion models/git/commit_status.go
Original file line number Diff line number Diff line change
Expand Up @@ -171,13 +171,17 @@ func GetNextCommitStatusIndex(ctx context.Context, repoID int64, sha string) (in
return newIdx, nil
}

func (status *CommitStatus) loadAttributes(ctx context.Context) (err error) {
func (status *CommitStatus) loadRepository(ctx context.Context) (err error) {
if status.Repo == nil {
status.Repo, err = repo_model.GetRepositoryByID(ctx, status.RepoID)
if err != nil {
return fmt.Errorf("getRepositoryByID [%d]: %w", status.RepoID, err)
}
}
return nil
}

func (status *CommitStatus) loadCreator(ctx context.Context) (err error) {
if status.Creator == nil && status.CreatorID > 0 {
status.Creator, err = user_model.GetUserByID(ctx, status.CreatorID)
if err != nil {
Expand All @@ -187,6 +191,13 @@ func (status *CommitStatus) loadAttributes(ctx context.Context) (err error) {
return nil
}

func (status *CommitStatus) loadAttributes(ctx context.Context) (err error) {
if err := status.loadRepository(ctx); err != nil {
return err
}
return status.loadCreator(ctx)
}

// APIURL returns the absolute APIURL to this commit-status.
func (status *CommitStatus) APIURL(ctx context.Context) string {
_ = status.loadAttributes(ctx)
Expand All @@ -198,6 +209,21 @@ func (status *CommitStatus) LocaleString(lang translation.Locale) string {
return lang.TrString("repo.commitstatus." + status.State.String())
}

// HideActionsURL set `TargetURL` to an empty string if the status comes from Gitea Actions
func (status *CommitStatus) HideActionsURL(ctx context.Context) {
if status.Repo == nil {
if err := status.loadRepository(ctx); err != nil {
log.Error("loadRepository: %v", err)
return
}
}

prefix := fmt.Sprintf("%s/actions", status.Repo.Link())
if strings.HasPrefix(status.TargetURL, prefix) {
status.TargetURL = ""
}
}

// CalcCommitStatus returns commit status state via some status, the commit statues should order by id desc
func CalcCommitStatus(statuses []*CommitStatus) *CommitStatus {
var lastStatus *CommitStatus
Expand Down Expand Up @@ -506,3 +532,15 @@ func ConvertFromGitCommit(ctx context.Context, commits []*git.Commit, repo *repo
repo,
)
}

// CommitStatusesHideActionsURL hide Gitea Actions urls
func CommitStatusesHideActionsURL(ctx context.Context, statuses []*CommitStatus) {
idToRepos := make(map[int64]*repo_model.Repository)
for _, status := range statuses {
if status.Repo == nil {
status.Repo = idToRepos[status.RepoID]
}
status.HideActionsURL(ctx)
idToRepos[status.RepoID] = status.Repo
}
}
25 changes: 25 additions & 0 deletions models/git/commit_status_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@
package git_test

import (
"fmt"
"testing"
"time"

actions_model "code.gitea.io/gitea/models/actions"
"code.gitea.io/gitea/models/db"
git_model "code.gitea.io/gitea/models/git"
repo_model "code.gitea.io/gitea/models/repo"
Expand Down Expand Up @@ -231,3 +233,26 @@ func TestFindRepoRecentCommitStatusContexts(t *testing.T) {
assert.Equal(t, "compliance/lint-backend", contexts[0])
}
}

func TestCommitStatusesHideActionsURL(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())

repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4})
run := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRun{ID: 791, RepoID: repo.ID})
assert.NoError(t, run.LoadAttributes(db.DefaultContext))

statuses := []*git_model.CommitStatus{
{
RepoID: repo.ID,
TargetURL: fmt.Sprintf("%s/jobs/%d", run.Link(), run.Index),
},
{
RepoID: repo.ID,
TargetURL: "https://mycicd.org/1",
},
}

git_model.CommitStatusesHideActionsURL(db.DefaultContext, statuses)
assert.Empty(t, statuses[0].TargetURL)
assert.Equal(t, "https://mycicd.org/1", statuses[1].TargetURL)
}
13 changes: 7 additions & 6 deletions models/repo/repo.go
Original file line number Diff line number Diff line change
Expand Up @@ -745,17 +745,18 @@ func GetRepositoryByOwnerAndName(ctx context.Context, ownerName, repoName string

// GetRepositoryByName returns the repository by given name under user if exists.
func GetRepositoryByName(ctx context.Context, ownerID int64, name string) (*Repository, error) {
repo := &Repository{
OwnerID: ownerID,
LowerName: strings.ToLower(name),
}
has, err := db.GetEngine(ctx).Get(repo)
var repo Repository
has, err := db.GetEngine(ctx).
Where("`owner_id`=?", ownerID).
And("`lower_name`=?", strings.ToLower(name)).
NoAutoCondition().
Get(&repo)
if err != nil {
return nil, err
} else if !has {
return nil, ErrRepoNotExist{0, ownerID, "", name}
}
return repo, err
return &repo, err
}

// getRepositoryURLPathSegments returns segments (owner, reponame) extracted from a url
Expand Down
1 change: 1 addition & 0 deletions models/user/email_address.go
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,7 @@ type SearchEmailOptions struct {

// SearchEmailResult is an e-mail address found in the user or email_address table
type SearchEmailResult struct {
ID int64
UID int64
Email string
IsActivated bool
Expand Down
2 changes: 2 additions & 0 deletions options/license/HIDAPI
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
This software may be used by anyone for any reason so long
as the copyright notice in the source files remains intact.
10 changes: 10 additions & 0 deletions options/license/Ruby-pty
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
(c) Copyright 1998 by Akinori Ito.

This software may be redistributed freely for this purpose, in full
or in part, provided that this entire copyright notice is included
on any copies of this software and applications and derivations thereof.

This software is provided on an "as is" basis, without warranty of any
kind, either expressed or implied, as to any matter including, but not
limited to warranty of fitness of purpose, or merchantability, or
results obtained from use of this software.
23 changes: 23 additions & 0 deletions options/license/X11-swapped
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
Copyright (c) 2008-2010 Derick Eddington. All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

Except as contained in this notice, the name(s) of the above copyright
holders shall not be used in advertising or otherwise to promote the sale,
use or other dealings in this Software without prior written authorization.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
6 changes: 6 additions & 0 deletions options/license/romic-exception
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
Additional permission under the GNU Affero GPL version 3 section 7:

If you modify this Program, or any covered work, by linking or
combining it with other code, such other code is not for that reason
alone subject to any of the requirements of the GNU Affero GPL
version 3.
4 changes: 4 additions & 0 deletions options/locale/locale_en-US.ini
Original file line number Diff line number Diff line change
Expand Up @@ -2982,6 +2982,10 @@ emails.not_updated = Failed to update the requested email address: %v
emails.duplicate_active = This email address is already active for a different user.
emails.change_email_header = Update Email Properties
emails.change_email_text = Are you sure you want to update this email address?
emails.delete = Delete Email
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.

orgs.org_manage_panel = Organization Management
orgs.name = Name
Expand Down
4 changes: 4 additions & 0 deletions options/locale/locale_pt-PT.ini
Original file line number Diff line number Diff line change
Expand Up @@ -2981,6 +2981,10 @@ emails.not_updated=Falhou a modificação do endereço de email solicitado: %v
emails.duplicate_active=Este endereço de email já está a ser usado por outro utilizador.
emails.change_email_header=Modificar propriedades do email
emails.change_email_text=Tem a certeza que quer modificar este endereço de email?
emails.delete=Eliminar email
emails.delete_desc=Tem a certeza que quer eliminar este endereço de email?
emails.deletion_success=O endereço de email foi eliminado.
emails.delete_primary_email_error=Não pode eliminar o email principal.

orgs.org_manage_panel=Gestão das organizações
orgs.name=Nome
Expand Down
8 changes: 7 additions & 1 deletion routers/api/v1/repo/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ func GetRawFile(ctx *context.APIContext) {
// ---
// summary: Get a file from a repository
// produces:
// - application/json
// - application/octet-stream
// parameters:
// - name: owner
// in: path
Expand All @@ -67,6 +67,8 @@ func GetRawFile(ctx *context.APIContext) {
// responses:
// 200:
// description: Returns raw file content.
// schema:
// type: file
// "404":
// "$ref": "#/responses/notFound"

Expand All @@ -92,6 +94,8 @@ func GetRawFileOrLFS(ctx *context.APIContext) {
// swagger:operation GET /repos/{owner}/{repo}/media/{filepath} repository repoGetRawFileOrLFS
// ---
// summary: Get a file or it's LFS object from a repository
// produces:
// - application/octet-stream
// parameters:
// - name: owner
// in: path
Expand All @@ -116,6 +120,8 @@ func GetRawFileOrLFS(ctx *context.APIContext) {
// responses:
// 200:
// description: Returns raw file content.
// schema:
// type: file
// "404":
// "$ref": "#/responses/notFound"

Expand Down
30 changes: 30 additions & 0 deletions routers/web/admin/emails.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"code.gitea.io/gitea/modules/optional"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/services/context"
"code.gitea.io/gitea/services/user"
)

const (
Expand Down Expand Up @@ -150,3 +151,32 @@ func ActivateEmail(ctx *context.Context) {
redirect.RawQuery = q.Encode()
ctx.Redirect(redirect.String())
}

// DeleteEmail serves a POST request for delete a user's email
func DeleteEmail(ctx *context.Context) {
u, err := user_model.GetUserByID(ctx, ctx.FormInt64("Uid"))
if err != nil || u == nil {
ctx.ServerError("GetUserByID", err)
return
}

email, err := user_model.GetEmailAddressByID(ctx, u.ID, ctx.FormInt64("id"))
if err != nil || email == nil {
ctx.ServerError("GetEmailAddressByID", err)
return
}

if err := user.DeleteEmailAddresses(ctx, u, []string{email.Email}); err != nil {
if user_model.IsErrPrimaryEmailCannotDelete(err) {
ctx.Flash.Error(ctx.Tr("admin.emails.delete_primary_email_error"))
ctx.JSONRedirect("")
return
}
ctx.ServerError("DeleteEmailAddresses", err)
return
}
log.Trace("Email address deleted: %s %s", u.Name, email.Email)

ctx.Flash.Success(ctx.Tr("admin.emails.deletion_success"))
ctx.JSONRedirect("")
}
12 changes: 8 additions & 4 deletions routers/web/auth/oauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,7 @@ func getOAuthGroupsForUser(ctx go_context.Context, user *user_model.User) ([]str

func parseBasicAuth(ctx *context.Context) (username, password string, err error) {
authHeader := ctx.Req.Header.Get("Authorization")
if authType, authData, ok := strings.Cut(authHeader, " "); ok && authType == "Basic" {
if authType, authData, ok := strings.Cut(authHeader, " "); ok && strings.EqualFold(authType, "Basic") {
return base.BasicAuthDecode(authData)
}
return "", "", errors.New("invalid basic authentication")
Expand All @@ -353,8 +353,9 @@ func IntrospectOAuth(ctx *context.Context) {
}

var response struct {
Active bool `json:"active"`
Scope string `json:"scope,omitempty"`
Active bool `json:"active"`
Scope string `json:"scope,omitempty"`
Username string `json:"username,omitempty"`
jwt.RegisteredClaims
}

Expand All @@ -371,6 +372,9 @@ func IntrospectOAuth(ctx *context.Context) {
response.Audience = []string{app.ClientID}
response.Subject = fmt.Sprint(grant.UserID)
}
if user, err := user_model.GetUserByID(ctx, grant.UserID); err == nil {
response.Username = user.Name
}
}
}

Expand Down Expand Up @@ -657,7 +661,7 @@ func AccessTokenOAuth(ctx *context.Context) {
// if there is no ClientID or ClientSecret in the request body, fill these fields by the Authorization header and ensure the provided field matches the Authorization header
if form.ClientID == "" || form.ClientSecret == "" {
authHeader := ctx.Req.Header.Get("Authorization")
if authType, authData, ok := strings.Cut(authHeader, " "); ok && authType == "Basic" {
if authType, authData, ok := strings.Cut(authHeader, " "); ok && strings.EqualFold(authType, "Basic") {
clientID, clientSecret, err := base.BasicAuthDecode(authData)
if err != nil {
handleAccessTokenError(ctx, AccessTokenError{
Expand Down
6 changes: 3 additions & 3 deletions routers/web/feed/convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ func feedActionsToFeedItems(ctx *context.Context, actions activities_model.Actio
link := &feeds.Link{Href: act.GetCommentHTMLURL(ctx)}

// title
title = act.ActUser.DisplayName() + " "
title = act.ActUser.GetDisplayName() + " "
var titleExtra template.HTML
switch act.OpType {
case activities_model.ActionCreateRepo:
Expand Down Expand Up @@ -252,7 +252,7 @@ func feedActionsToFeedItems(ctx *context.Context, actions activities_model.Actio
Description: desc,
IsPermaLink: "false",
Author: &feeds.Author{
Name: act.ActUser.DisplayName(),
Name: act.ActUser.GetDisplayName(),
Email: act.ActUser.GetEmail(),
},
Id: fmt.Sprintf("%v: %v", strconv.FormatInt(act.ID, 10), link.Href),
Expand Down Expand Up @@ -313,7 +313,7 @@ func releasesToFeedItems(ctx *context.Context, releases []*repo_model.Release) (
Link: link,
Created: rel.CreatedUnix.AsTime(),
Author: &feeds.Author{
Name: rel.Publisher.DisplayName(),
Name: rel.Publisher.GetDisplayName(),
Email: rel.Publisher.GetEmail(),
},
Id: fmt.Sprintf("%v: %v", strconv.FormatInt(rel.ID, 10), link.Href),
Expand Down
Loading

0 comments on commit 5481812

Please sign in to comment.