repo stringlengths 6 47 | file_url stringlengths 77 269 | file_path stringlengths 5 186 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-07 08:35:43 2026-01-07 08:55:24 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/comment.go | internal/database/comment.go | // Copyright 2016 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"context"
"fmt"
"strings"
"time"
"github.com/unknwon/com"
log "unknwon.dev/clog/v2"
"xorm.io/xorm"
api "github.com/gogs/go-gogs-client"
"gogs.io/gogs/internal/errutil"
"gogs.io/gogs/internal/markup"
)
// CommentType defines whether a comment is just a simple comment, an action (like close) or a reference.
type CommentType int
const (
// Plain comment, can be associated with a commit (CommitID > 0) and a line (LineNum > 0)
CommentTypeComment CommentType = iota
CommentTypeReopen
CommentTypeClose
// References.
CommentTypeIssueRef
// Reference from a commit (not part of a pull request)
CommentTypeCommitRef
// Reference from a comment
CommentTypeCommentRef
// Reference from a pull request
CommentTypePullRef
)
type CommentTag int
const (
CommentTagNone CommentTag = iota
CommentTagPoster
CommentTagWriter
CommentTagOwner
)
// Comment represents a comment in commit and issue page.
type Comment struct {
ID int64
Type CommentType
PosterID int64
Poster *User `xorm:"-" json:"-" gorm:"-"`
IssueID int64 `xorm:"INDEX"`
Issue *Issue `xorm:"-" json:"-" gorm:"-"`
CommitID int64
Line int64
Content string `xorm:"TEXT"`
RenderedContent string `xorm:"-" json:"-" gorm:"-"`
Created time.Time `xorm:"-" json:"-" gorm:"-"`
CreatedUnix int64
Updated time.Time `xorm:"-" json:"-" gorm:"-"`
UpdatedUnix int64
// Reference issue in commit message
CommitSHA string `xorm:"VARCHAR(40)"`
Attachments []*Attachment `xorm:"-" json:"-" gorm:"-"`
// For view issue page.
ShowTag CommentTag `xorm:"-" json:"-" gorm:"-"`
}
func (c *Comment) BeforeInsert() {
c.CreatedUnix = time.Now().Unix()
c.UpdatedUnix = c.CreatedUnix
}
func (c *Comment) BeforeUpdate() {
c.UpdatedUnix = time.Now().Unix()
}
func (c *Comment) AfterSet(colName string, _ xorm.Cell) {
switch colName {
case "created_unix":
c.Created = time.Unix(c.CreatedUnix, 0).Local()
case "updated_unix":
c.Updated = time.Unix(c.UpdatedUnix, 0).Local()
}
}
func (c *Comment) loadAttributes(e Engine) (err error) {
if c.Poster == nil {
c.Poster, err = Handle.Users().GetByID(context.TODO(), c.PosterID)
if err != nil {
if IsErrUserNotExist(err) {
c.PosterID = -1
c.Poster = NewGhostUser()
} else {
return fmt.Errorf("getUserByID.(Poster) [%d]: %v", c.PosterID, err)
}
}
}
if c.Issue == nil {
c.Issue, err = getRawIssueByID(e, c.IssueID)
if err != nil {
return fmt.Errorf("getIssueByID [%d]: %v", c.IssueID, err)
}
if c.Issue.Repo == nil {
c.Issue.Repo, err = getRepositoryByID(e, c.Issue.RepoID)
if err != nil {
return fmt.Errorf("getRepositoryByID [%d]: %v", c.Issue.RepoID, err)
}
}
}
if c.Attachments == nil {
c.Attachments, err = getAttachmentsByCommentID(e, c.ID)
if err != nil {
return fmt.Errorf("getAttachmentsByCommentID [%d]: %v", c.ID, err)
}
}
return nil
}
func (c *Comment) LoadAttributes() error {
return c.loadAttributes(x)
}
func (c *Comment) HTMLURL() string {
return fmt.Sprintf("%s#issuecomment-%d", c.Issue.HTMLURL(), c.ID)
}
// This method assumes following fields have been assigned with valid values:
// Required - Poster, Issue
func (c *Comment) APIFormat() *api.Comment {
return &api.Comment{
ID: c.ID,
HTMLURL: c.HTMLURL(),
Poster: c.Poster.APIFormat(),
Body: c.Content,
Created: c.Created,
Updated: c.Updated,
}
}
func CommentHashTag(id int64) string {
return "issuecomment-" + com.ToStr(id)
}
// HashTag returns unique hash tag for comment.
func (c *Comment) HashTag() string {
return CommentHashTag(c.ID)
}
// EventTag returns unique event hash tag for comment.
func (c *Comment) EventTag() string {
return "event-" + com.ToStr(c.ID)
}
// mailParticipants sends new comment emails to repository watchers
// and mentioned people.
func (c *Comment) mailParticipants(e Engine, opType ActionType, issue *Issue) (err error) {
mentions := markup.FindAllMentions(c.Content)
if err = updateIssueMentions(e, c.IssueID, mentions); err != nil {
return fmt.Errorf("UpdateIssueMentions [%d]: %v", c.IssueID, err)
}
switch opType {
case ActionCommentIssue:
issue.Content = c.Content
case ActionCloseIssue:
issue.Content = fmt.Sprintf("Closed #%d", issue.Index)
case ActionReopenIssue:
issue.Content = fmt.Sprintf("Reopened #%d", issue.Index)
}
if err = mailIssueCommentToParticipants(issue, c.Poster, mentions); err != nil {
log.Error("mailIssueCommentToParticipants: %v", err)
}
return nil
}
func createComment(e *xorm.Session, opts *CreateCommentOptions) (_ *Comment, err error) {
comment := &Comment{
Type: opts.Type,
PosterID: opts.Doer.ID,
Poster: opts.Doer,
IssueID: opts.Issue.ID,
CommitID: opts.CommitID,
CommitSHA: opts.CommitSHA,
Line: opts.LineNum,
Content: opts.Content,
}
if _, err = e.Insert(comment); err != nil {
return nil, err
}
// Compose comment action, could be plain comment, close or reopen issue/pull request.
// This object will be used to notify watchers in the end of function.
act := &Action{
ActUserID: opts.Doer.ID,
ActUserName: opts.Doer.Name,
Content: fmt.Sprintf("%d|%s", opts.Issue.Index, strings.Split(opts.Content, "\n")[0]),
RepoID: opts.Repo.ID,
RepoUserName: opts.Repo.Owner.Name,
RepoName: opts.Repo.Name,
IsPrivate: opts.Repo.IsPrivate,
}
// Check comment type.
switch opts.Type {
case CommentTypeComment:
act.OpType = ActionCommentIssue
if _, err = e.Exec("UPDATE `issue` SET num_comments=num_comments+1 WHERE id=?", opts.Issue.ID); err != nil {
return nil, err
}
// Check attachments
attachments := make([]*Attachment, 0, len(opts.Attachments))
for _, uuid := range opts.Attachments {
attach, err := getAttachmentByUUID(e, uuid)
if err != nil {
if IsErrAttachmentNotExist(err) {
continue
}
return nil, fmt.Errorf("getAttachmentByUUID [%s]: %v", uuid, err)
}
attachments = append(attachments, attach)
}
for i := range attachments {
attachments[i].IssueID = opts.Issue.ID
attachments[i].CommentID = comment.ID
// No assign value could be 0, so ignore AllCols().
if _, err = e.ID(attachments[i].ID).Update(attachments[i]); err != nil {
return nil, fmt.Errorf("update attachment [%d]: %v", attachments[i].ID, err)
}
}
case CommentTypeReopen:
act.OpType = ActionReopenIssue
if opts.Issue.IsPull {
act.OpType = ActionReopenPullRequest
}
if opts.Issue.IsPull {
_, err = e.Exec("UPDATE `repository` SET num_closed_pulls=num_closed_pulls-1 WHERE id=?", opts.Repo.ID)
} else {
_, err = e.Exec("UPDATE `repository` SET num_closed_issues=num_closed_issues-1 WHERE id=?", opts.Repo.ID)
}
if err != nil {
return nil, err
}
case CommentTypeClose:
act.OpType = ActionCloseIssue
if opts.Issue.IsPull {
act.OpType = ActionClosePullRequest
}
if opts.Issue.IsPull {
_, err = e.Exec("UPDATE `repository` SET num_closed_pulls=num_closed_pulls+1 WHERE id=?", opts.Repo.ID)
} else {
_, err = e.Exec("UPDATE `repository` SET num_closed_issues=num_closed_issues+1 WHERE id=?", opts.Repo.ID)
}
if err != nil {
return nil, err
}
}
if _, err = e.Exec("UPDATE `issue` SET updated_unix = ? WHERE id = ?", time.Now().Unix(), opts.Issue.ID); err != nil {
return nil, fmt.Errorf("update issue 'updated_unix': %v", err)
}
// Notify watchers for whatever action comes in, ignore if no action type.
if act.OpType > 0 {
if err = notifyWatchers(e, act); err != nil {
log.Error("notifyWatchers: %v", err)
}
if err = comment.mailParticipants(e, act.OpType, opts.Issue); err != nil {
log.Error("MailParticipants: %v", err)
}
}
return comment, comment.loadAttributes(e)
}
func createStatusComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue) (*Comment, error) {
cmtType := CommentTypeClose
if !issue.IsClosed {
cmtType = CommentTypeReopen
}
return createComment(e, &CreateCommentOptions{
Type: cmtType,
Doer: doer,
Repo: repo,
Issue: issue,
})
}
type CreateCommentOptions struct {
Type CommentType
Doer *User
Repo *Repository
Issue *Issue
CommitID int64
CommitSHA string
LineNum int64
Content string
Attachments []string // UUIDs of attachments
}
// CreateComment creates comment of issue or commit.
func CreateComment(opts *CreateCommentOptions) (comment *Comment, err error) {
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return nil, err
}
comment, err = createComment(sess, opts)
if err != nil {
return nil, err
}
return comment, sess.Commit()
}
// CreateIssueComment creates a plain issue comment.
func CreateIssueComment(doer *User, repo *Repository, issue *Issue, content string, attachments []string) (*Comment, error) {
comment, err := CreateComment(&CreateCommentOptions{
Type: CommentTypeComment,
Doer: doer,
Repo: repo,
Issue: issue,
Content: content,
Attachments: attachments,
})
if err != nil {
return nil, fmt.Errorf("CreateComment: %v", err)
}
comment.Issue = issue
if err = PrepareWebhooks(repo, HookEventTypeIssueComment, &api.IssueCommentPayload{
Action: api.HOOK_ISSUE_COMMENT_CREATED,
Issue: issue.APIFormat(),
Comment: comment.APIFormat(),
Repository: repo.APIFormatLegacy(nil),
Sender: doer.APIFormat(),
}); err != nil {
log.Error("PrepareWebhooks [comment_id: %d]: %v", comment.ID, err)
}
return comment, nil
}
// CreateRefComment creates a commit reference comment to issue.
func CreateRefComment(doer *User, repo *Repository, issue *Issue, content, commitSHA string) error {
if commitSHA == "" {
return fmt.Errorf("cannot create reference with empty commit SHA")
}
// Check if same reference from same commit has already existed.
has, err := x.Get(&Comment{
Type: CommentTypeCommitRef,
IssueID: issue.ID,
CommitSHA: commitSHA,
})
if err != nil {
return fmt.Errorf("check reference comment: %v", err)
} else if has {
return nil
}
_, err = CreateComment(&CreateCommentOptions{
Type: CommentTypeCommitRef,
Doer: doer,
Repo: repo,
Issue: issue,
CommitSHA: commitSHA,
Content: content,
})
return err
}
var _ errutil.NotFound = (*ErrCommentNotExist)(nil)
type ErrCommentNotExist struct {
args map[string]any
}
func IsErrCommentNotExist(err error) bool {
_, ok := err.(ErrCommentNotExist)
return ok
}
func (err ErrCommentNotExist) Error() string {
return fmt.Sprintf("comment does not exist: %v", err.args)
}
func (ErrCommentNotExist) NotFound() bool {
return true
}
// GetCommentByID returns the comment by given ID.
func GetCommentByID(id int64) (*Comment, error) {
c := new(Comment)
has, err := x.Id(id).Get(c)
if err != nil {
return nil, err
} else if !has {
return nil, ErrCommentNotExist{args: map[string]any{"commentID": id}}
}
return c, c.LoadAttributes()
}
// FIXME: use CommentList to improve performance.
func loadCommentsAttributes(e Engine, comments []*Comment) (err error) {
for i := range comments {
if err = comments[i].loadAttributes(e); err != nil {
return fmt.Errorf("loadAttributes [%d]: %v", comments[i].ID, err)
}
}
return nil
}
func getCommentsByIssueIDSince(e Engine, issueID, since int64) ([]*Comment, error) {
comments := make([]*Comment, 0, 10)
sess := e.Where("issue_id = ?", issueID).Asc("created_unix")
if since > 0 {
sess.And("updated_unix >= ?", since)
}
if err := sess.Find(&comments); err != nil {
return nil, err
}
return comments, loadCommentsAttributes(e, comments)
}
func getCommentsByRepoIDSince(e Engine, repoID, since int64) ([]*Comment, error) {
comments := make([]*Comment, 0, 10)
sess := e.Where("issue.repo_id = ?", repoID).Join("INNER", "issue", "issue.id = comment.issue_id").Asc("comment.created_unix")
if since > 0 {
sess.And("comment.updated_unix >= ?", since)
}
if err := sess.Find(&comments); err != nil {
return nil, err
}
return comments, loadCommentsAttributes(e, comments)
}
func getCommentsByIssueID(e Engine, issueID int64) ([]*Comment, error) {
return getCommentsByIssueIDSince(e, issueID, -1)
}
// GetCommentsByIssueID returns all comments of an issue.
func GetCommentsByIssueID(issueID int64) ([]*Comment, error) {
return getCommentsByIssueID(x, issueID)
}
// GetCommentsByIssueIDSince returns a list of comments of an issue since a given time point.
func GetCommentsByIssueIDSince(issueID, since int64) ([]*Comment, error) {
return getCommentsByIssueIDSince(x, issueID, since)
}
// GetCommentsByRepoIDSince returns a list of comments for all issues in a repo since a given time point.
func GetCommentsByRepoIDSince(repoID, since int64) ([]*Comment, error) {
return getCommentsByRepoIDSince(x, repoID, since)
}
// UpdateComment updates information of comment.
func UpdateComment(doer *User, c *Comment, oldContent string) (err error) {
if _, err = x.Id(c.ID).AllCols().Update(c); err != nil {
return err
}
if err = c.Issue.LoadAttributes(); err != nil {
log.Error("Issue.LoadAttributes [issue_id: %d]: %v", c.IssueID, err)
} else if err = PrepareWebhooks(c.Issue.Repo, HookEventTypeIssueComment, &api.IssueCommentPayload{
Action: api.HOOK_ISSUE_COMMENT_EDITED,
Issue: c.Issue.APIFormat(),
Comment: c.APIFormat(),
Changes: &api.ChangesPayload{
Body: &api.ChangesFromPayload{
From: oldContent,
},
},
Repository: c.Issue.Repo.APIFormatLegacy(nil),
Sender: doer.APIFormat(),
}); err != nil {
log.Error("PrepareWebhooks [comment_id: %d]: %v", c.ID, err)
}
return nil
}
// DeleteCommentByID deletes the comment by given ID.
func DeleteCommentByID(doer *User, id int64) error {
comment, err := GetCommentByID(id)
if err != nil {
if IsErrCommentNotExist(err) {
return nil
}
return err
}
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if _, err = sess.ID(comment.ID).Delete(new(Comment)); err != nil {
return err
}
if comment.Type == CommentTypeComment {
if _, err = sess.Exec("UPDATE `issue` SET num_comments = num_comments - 1 WHERE id = ?", comment.IssueID); err != nil {
return err
}
}
if err = sess.Commit(); err != nil {
return fmt.Errorf("commit: %v", err)
}
_, err = DeleteAttachmentsByComment(comment.ID, true)
if err != nil {
log.Error("Failed to delete attachments by comment[%d]: %v", comment.ID, err)
}
if err = comment.Issue.LoadAttributes(); err != nil {
log.Error("Issue.LoadAttributes [issue_id: %d]: %v", comment.IssueID, err)
} else if err = PrepareWebhooks(comment.Issue.Repo, HookEventTypeIssueComment, &api.IssueCommentPayload{
Action: api.HOOK_ISSUE_COMMENT_DELETED,
Issue: comment.Issue.APIFormat(),
Comment: comment.APIFormat(),
Repository: comment.Issue.Repo.APIFormatLegacy(nil),
Sender: doer.APIFormat(),
}); err != nil {
log.Error("PrepareWebhooks [comment_id: %d]: %v", comment.ID, err)
}
return nil
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/backup_test.go | internal/database/backup_test.go | // Copyright 2020 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"bytes"
"context"
"os"
"path/filepath"
"testing"
"time"
"github.com/pkg/errors"
"github.com/stretchr/testify/require"
"gorm.io/gorm"
"gogs.io/gogs/internal/auth"
"gogs.io/gogs/internal/auth/github"
"gogs.io/gogs/internal/auth/pam"
"gogs.io/gogs/internal/cryptoutil"
"gogs.io/gogs/internal/dbtest"
"gogs.io/gogs/internal/lfsutil"
"gogs.io/gogs/internal/testutil"
)
func TestDumpAndImport(t *testing.T) {
if testing.Short() {
t.Skip()
}
t.Parallel()
const wantTables = 8
if len(Tables) != wantTables {
t.Fatalf("New table has added (want %d got %d), please add new tests for the table and update this check", wantTables, len(Tables))
}
db := dbtest.NewDB(t, "dumpAndImport", Tables...)
setupDBToDump(t, db)
dumpTables(t, db)
importTables(t, db)
// Dump and assert golden again to make sure data aren't changed.
dumpTables(t, db)
}
func setupDBToDump(t *testing.T, db *gorm.DB) {
vals := []any{
&Access{
ID: 1,
UserID: 1,
RepoID: 11,
Mode: AccessModeRead,
},
&Access{
ID: 2,
UserID: 2,
RepoID: 22,
Mode: AccessModeWrite,
},
&AccessToken{
UserID: 1,
Name: "test1",
Sha1: cryptoutil.SHA1("2910d03d-c0b5-4f71-bad5-c4086e4efae3"),
SHA256: cryptoutil.SHA256(cryptoutil.SHA1("2910d03d-c0b5-4f71-bad5-c4086e4efae3")),
CreatedUnix: 1588568886,
UpdatedUnix: 1588572486, // 1 hour later
},
&AccessToken{
UserID: 1,
Name: "test2",
Sha1: cryptoutil.SHA1("84117e17-7e67-4024-bd04-1c23e6e809d4"),
SHA256: cryptoutil.SHA256(cryptoutil.SHA1("84117e17-7e67-4024-bd04-1c23e6e809d4")),
CreatedUnix: 1588568886,
},
&AccessToken{
UserID: 2,
Name: "test1",
Sha1: cryptoutil.SHA1("da2775ce-73dd-47ba-b9d2-bbcc346585c4"),
SHA256: cryptoutil.SHA256(cryptoutil.SHA1("da2775ce-73dd-47ba-b9d2-bbcc346585c4")),
CreatedUnix: 1588568886,
},
&AccessToken{
UserID: 2,
Name: "test2",
Sha1: cryptoutil.SHA256(cryptoutil.SHA1("1b2dccd1-a262-470f-bb8c-7fc73192e9bb"))[:40],
SHA256: cryptoutil.SHA256(cryptoutil.SHA1("1b2dccd1-a262-470f-bb8c-7fc73192e9bb")),
CreatedUnix: 1588568886,
},
&Action{
ID: 1,
UserID: 1,
OpType: ActionCreateBranch,
ActUserID: 1,
ActUserName: "alice",
RepoID: 1,
RepoUserName: "alice",
RepoName: "example",
RefName: "main",
IsPrivate: false,
Content: `{"Len":1,"Commits":[],"CompareURL":""}`,
CreatedUnix: 1588568886,
},
&Action{
ID: 2,
UserID: 1,
OpType: ActionCommitRepo,
ActUserID: 1,
ActUserName: "alice",
RepoID: 1,
RepoUserName: "alice",
RepoName: "example",
RefName: "main",
IsPrivate: false,
Content: `{"Len":1,"Commits":[],"CompareURL":""}`,
CreatedUnix: 1588568886,
},
&Action{
ID: 3,
UserID: 1,
OpType: ActionDeleteBranch,
ActUserID: 1,
ActUserName: "alice",
RepoID: 1,
RepoUserName: "alice",
RepoName: "example",
RefName: "main",
IsPrivate: false,
CreatedUnix: 1588568886,
},
&EmailAddress{
ID: 1,
UserID: 1,
Email: "alice@example.com",
IsActivated: false,
},
&EmailAddress{
ID: 2,
UserID: 2,
Email: "bob@example.com",
IsActivated: true,
},
&Follow{
ID: 1,
UserID: 1,
FollowID: 2,
},
&Follow{
ID: 2,
UserID: 2,
FollowID: 1,
},
&LFSObject{
RepoID: 1,
OID: "ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f",
Size: 100,
Storage: lfsutil.StorageLocal,
CreatedAt: time.Unix(1588568886, 0).UTC(),
},
&LFSObject{
RepoID: 2,
OID: "ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f",
Size: 100,
Storage: lfsutil.StorageLocal,
CreatedAt: time.Unix(1588568886, 0).UTC(),
},
&LoginSource{
Type: auth.PAM,
Name: "My PAM",
IsActived: true,
Provider: pam.NewProvider(&pam.Config{
ServiceName: "PAM service",
}),
CreatedUnix: 1588568886,
UpdatedUnix: 1588572486, // 1 hour later
},
&LoginSource{
Type: auth.GitHub,
Name: "GitHub.com",
IsActived: true,
Provider: github.NewProvider(&github.Config{
APIEndpoint: "https://api.github.com",
}),
CreatedUnix: 1588568886,
},
&Notice{
ID: 1,
Type: NoticeTypeRepository,
Description: "This is a notice",
CreatedUnix: 1588568886,
},
}
for _, val := range vals {
err := db.Create(val).Error
require.NoError(t, err)
}
}
func dumpTables(t *testing.T, db *gorm.DB) {
ctx := context.Background()
for _, table := range Tables {
tableName := getTableType(table)
var buf bytes.Buffer
err := dumpTable(ctx, db, table, &buf)
if err != nil {
t.Fatalf("%s: %v", tableName, err)
}
golden := filepath.Join("testdata", "backup", tableName+".golden.json")
testutil.AssertGolden(t, golden, testutil.Update("TestDumpAndImport"), buf.String())
}
}
func importTables(t *testing.T, db *gorm.DB) {
ctx := context.Background()
for _, table := range Tables {
tableName := getTableType(table)
err := func() error {
golden := filepath.Join("testdata", "backup", tableName+".golden.json")
f, err := os.Open(golden)
if err != nil {
return errors.Wrap(err, "open table file")
}
defer func() { _ = f.Close() }()
return importTable(ctx, db, table, f)
}()
if err != nil {
t.Fatalf("%s: %v", tableName, err)
}
}
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/repositories_test.go | internal/database/repositories_test.go | // Copyright 2020 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gorm.io/gorm"
"gogs.io/gogs/internal/errutil"
)
func TestRepository_BeforeCreate(t *testing.T) {
now := time.Now()
db := &gorm.DB{
Config: &gorm.Config{
SkipDefaultTransaction: true,
NowFunc: func() time.Time {
return now
},
},
}
t.Run("CreatedUnix has been set", func(t *testing.T) {
repo := &Repository{
CreatedUnix: 1,
}
_ = repo.BeforeCreate(db)
assert.Equal(t, int64(1), repo.CreatedUnix)
})
t.Run("CreatedUnix has not been set", func(t *testing.T) {
repo := &Repository{}
_ = repo.BeforeCreate(db)
assert.Equal(t, db.NowFunc().Unix(), repo.CreatedUnix)
})
}
func TestRepository_BeforeUpdate(t *testing.T) {
now := time.Now()
db := &gorm.DB{
Config: &gorm.Config{
SkipDefaultTransaction: true,
NowFunc: func() time.Time {
return now
},
},
}
repo := &Repository{}
_ = repo.BeforeUpdate(db)
assert.Equal(t, db.NowFunc().Unix(), repo.UpdatedUnix)
}
func TestRepository_AfterFind(t *testing.T) {
now := time.Now()
db := &gorm.DB{
Config: &gorm.Config{
SkipDefaultTransaction: true,
NowFunc: func() time.Time {
return now
},
},
}
repo := &Repository{
CreatedUnix: now.Unix(),
UpdatedUnix: now.Unix(),
}
_ = repo.AfterFind(db)
assert.Equal(t, repo.CreatedUnix, repo.Created.Unix())
assert.Equal(t, repo.UpdatedUnix, repo.Updated.Unix())
}
func TestRepos(t *testing.T) {
if testing.Short() {
t.Skip()
}
t.Parallel()
ctx := context.Background()
s := &RepositoriesStore{
db: newTestDB(t, "repos"),
}
for _, tc := range []struct {
name string
test func(t *testing.T, ctx context.Context, s *RepositoriesStore)
}{
{"Create", reposCreate},
{"GetByCollaboratorID", reposGetByCollaboratorID},
{"GetByCollaboratorIDWithAccessMode", reposGetByCollaboratorIDWithAccessMode},
{"GetByID", reposGetByID},
{"GetByName", reposGetByName},
{"Star", reposStar},
{"Touch", reposTouch},
{"ListByRepo", reposListWatches},
{"Watch", reposWatch},
{"HasForkedBy", reposHasForkedBy},
} {
t.Run(tc.name, func(t *testing.T) {
t.Cleanup(func() {
err := clearTables(t, s.db)
require.NoError(t, err)
})
tc.test(t, ctx, s)
})
if t.Failed() {
break
}
}
}
func reposCreate(t *testing.T, ctx context.Context, s *RepositoriesStore) {
t.Run("name not allowed", func(t *testing.T) {
_, err := s.Create(ctx,
1,
CreateRepoOptions{
Name: "my.git",
},
)
wantErr := ErrNameNotAllowed{args: errutil.Args{"reason": "reserved", "pattern": "*.git"}}
assert.Equal(t, wantErr, err)
})
t.Run("already exists", func(t *testing.T) {
_, err := s.Create(ctx, 2,
CreateRepoOptions{
Name: "repo1",
},
)
require.NoError(t, err)
_, err = s.Create(ctx, 2,
CreateRepoOptions{
Name: "repo1",
},
)
wantErr := ErrRepoAlreadyExist{args: errutil.Args{"ownerID": int64(2), "name": "repo1"}}
assert.Equal(t, wantErr, err)
})
repo, err := s.Create(ctx, 3,
CreateRepoOptions{
Name: "repo2",
},
)
require.NoError(t, err)
repo, err = s.GetByName(ctx, repo.OwnerID, repo.Name)
require.NoError(t, err)
assert.Equal(t, s.db.NowFunc().Format(time.RFC3339), repo.Created.UTC().Format(time.RFC3339))
assert.Equal(t, 1, repo.NumWatches) // The owner is watching the repo by default.
}
func reposGetByCollaboratorID(t *testing.T, ctx context.Context, s *RepositoriesStore) {
repo1, err := s.Create(ctx, 1, CreateRepoOptions{Name: "repo1"})
require.NoError(t, err)
repo2, err := s.Create(ctx, 2, CreateRepoOptions{Name: "repo2"})
require.NoError(t, err)
permissionsStore := newPermissionsStore(s.db)
err = permissionsStore.SetRepoPerms(ctx, repo1.ID, map[int64]AccessMode{3: AccessModeRead})
require.NoError(t, err)
err = permissionsStore.SetRepoPerms(ctx, repo2.ID, map[int64]AccessMode{4: AccessModeAdmin})
require.NoError(t, err)
t.Run("user 3 is a collaborator of repo1", func(t *testing.T) {
got, err := s.GetByCollaboratorID(ctx, 3, 10, "")
require.NoError(t, err)
require.Len(t, got, 1)
assert.Equal(t, repo1.ID, got[0].ID)
})
t.Run("do not return directly owned repository", func(t *testing.T) {
got, err := s.GetByCollaboratorID(ctx, 1, 10, "")
require.NoError(t, err)
require.Len(t, got, 0)
})
}
func reposGetByCollaboratorIDWithAccessMode(t *testing.T, ctx context.Context, s *RepositoriesStore) {
repo1, err := s.Create(ctx, 1, CreateRepoOptions{Name: "repo1"})
require.NoError(t, err)
repo2, err := s.Create(ctx, 2, CreateRepoOptions{Name: "repo2"})
require.NoError(t, err)
repo3, err := s.Create(ctx, 2, CreateRepoOptions{Name: "repo3"})
require.NoError(t, err)
permissionsStore := newPermissionsStore(s.db)
err = permissionsStore.SetRepoPerms(ctx, repo1.ID, map[int64]AccessMode{3: AccessModeRead})
require.NoError(t, err)
err = permissionsStore.SetRepoPerms(ctx, repo2.ID, map[int64]AccessMode{3: AccessModeAdmin, 4: AccessModeWrite})
require.NoError(t, err)
err = permissionsStore.SetRepoPerms(ctx, repo3.ID, map[int64]AccessMode{4: AccessModeWrite})
require.NoError(t, err)
got, err := s.GetByCollaboratorIDWithAccessMode(ctx, 3)
require.NoError(t, err)
require.Len(t, got, 2)
accessModes := make(map[int64]AccessMode)
for repo, mode := range got {
accessModes[repo.ID] = mode
}
assert.Equal(t, AccessModeRead, accessModes[repo1.ID])
assert.Equal(t, AccessModeAdmin, accessModes[repo2.ID])
}
func reposGetByID(t *testing.T, ctx context.Context, s *RepositoriesStore) {
repo1, err := s.Create(ctx, 1, CreateRepoOptions{Name: "repo1"})
require.NoError(t, err)
got, err := s.GetByID(ctx, repo1.ID)
require.NoError(t, err)
assert.Equal(t, repo1.Name, got.Name)
_, err = s.GetByID(ctx, 404)
wantErr := ErrRepoNotExist{args: errutil.Args{"repoID": int64(404)}}
assert.Equal(t, wantErr, err)
}
func reposGetByName(t *testing.T, ctx context.Context, s *RepositoriesStore) {
repo, err := s.Create(ctx, 1,
CreateRepoOptions{
Name: "repo1",
},
)
require.NoError(t, err)
_, err = s.GetByName(ctx, repo.OwnerID, repo.Name)
require.NoError(t, err)
_, err = s.GetByName(ctx, 1, "bad_name")
wantErr := ErrRepoNotExist{args: errutil.Args{"ownerID": int64(1), "name": "bad_name"}}
assert.Equal(t, wantErr, err)
}
func reposStar(t *testing.T, ctx context.Context, s *RepositoriesStore) {
repo1, err := s.Create(ctx, 1, CreateRepoOptions{Name: "repo1"})
require.NoError(t, err)
usersStore := newUsersStore(s.db)
alice, err := usersStore.Create(ctx, "alice", "alice@example.com", CreateUserOptions{})
require.NoError(t, err)
err = s.Star(ctx, alice.ID, repo1.ID)
require.NoError(t, err)
repo1, err = s.GetByID(ctx, repo1.ID)
require.NoError(t, err)
assert.Equal(t, 1, repo1.NumStars)
alice, err = usersStore.GetByID(ctx, alice.ID)
require.NoError(t, err)
assert.Equal(t, 1, alice.NumStars)
}
func reposTouch(t *testing.T, ctx context.Context, s *RepositoriesStore) {
repo, err := s.Create(ctx, 1,
CreateRepoOptions{
Name: "repo1",
},
)
require.NoError(t, err)
err = s.db.WithContext(ctx).Model(new(Repository)).Where("id = ?", repo.ID).Update("is_bare", true).Error
require.NoError(t, err)
// Make sure it is bare
got, err := s.GetByName(ctx, repo.OwnerID, repo.Name)
require.NoError(t, err)
assert.True(t, got.IsBare)
// Touch it
err = s.Touch(ctx, repo.ID)
require.NoError(t, err)
// It should not be bare anymore
got, err = s.GetByName(ctx, repo.OwnerID, repo.Name)
require.NoError(t, err)
assert.False(t, got.IsBare)
}
func reposListWatches(t *testing.T, ctx context.Context, s *RepositoriesStore) {
err := s.Watch(ctx, 1, 1)
require.NoError(t, err)
err = s.Watch(ctx, 2, 1)
require.NoError(t, err)
err = s.Watch(ctx, 2, 2)
require.NoError(t, err)
got, err := s.ListWatches(ctx, 1)
require.NoError(t, err)
for _, w := range got {
w.ID = 0
}
want := []*Watch{
{UserID: 1, RepoID: 1},
{UserID: 2, RepoID: 1},
}
assert.Equal(t, want, got)
}
func reposWatch(t *testing.T, ctx context.Context, s *RepositoriesStore) {
reposStore := newReposStore(s.db)
repo1, err := reposStore.Create(ctx, 1, CreateRepoOptions{Name: "repo1"})
require.NoError(t, err)
err = s.Watch(ctx, 2, repo1.ID)
require.NoError(t, err)
// It is OK to watch multiple times and just be noop.
err = s.Watch(ctx, 2, repo1.ID)
require.NoError(t, err)
repo1, err = reposStore.GetByID(ctx, repo1.ID)
require.NoError(t, err)
assert.Equal(t, 2, repo1.NumWatches) // The owner is watching the repo by default.
}
func reposHasForkedBy(t *testing.T, ctx context.Context, s *RepositoriesStore) {
has := s.HasForkedBy(ctx, 1, 2)
assert.False(t, has)
_, err := newReposStore(s.db).Create(
ctx,
2,
CreateRepoOptions{
Name: "repo1",
ForkID: 1,
},
)
require.NoError(t, err)
has = s.HasForkedBy(ctx, 1, 2)
assert.True(t, has)
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/organizations_test.go | internal/database/organizations_test.go | // Copyright 2022 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gogs.io/gogs/internal/dbutil"
)
func TestOrgs(t *testing.T) {
if testing.Short() {
t.Skip()
}
t.Parallel()
ctx := context.Background()
s := &OrganizationsStore{
db: newTestDB(t, "OrganizationsStore"),
}
for _, tc := range []struct {
name string
test func(t *testing.T, ctx context.Context, s *OrganizationsStore)
}{
{"List", orgsList},
{"SearchByName", organizationsSearchByName},
{"CountByUser", organizationsCountByUser},
} {
t.Run(tc.name, func(t *testing.T) {
t.Cleanup(func() {
err := clearTables(t, s.db)
require.NoError(t, err)
})
tc.test(t, ctx, s)
})
if t.Failed() {
break
}
}
}
func orgsList(t *testing.T, ctx context.Context, s *OrganizationsStore) {
usersStore := newUsersStore(s.db)
alice, err := usersStore.Create(ctx, "alice", "alice@example.com", CreateUserOptions{})
require.NoError(t, err)
bob, err := usersStore.Create(ctx, "bob", "bob@example.com", CreateUserOptions{})
require.NoError(t, err)
// TODO: Use Orgs.Create to replace SQL hack when the method is available.
org1, err := usersStore.Create(ctx, "org1", "org1@example.com", CreateUserOptions{})
require.NoError(t, err)
org2, err := usersStore.Create(ctx, "org2", "org2@example.com", CreateUserOptions{})
require.NoError(t, err)
err = s.db.Exec(
dbutil.Quote("UPDATE %s SET type = ? WHERE id IN (?, ?)", "user"),
UserTypeOrganization, org1.ID, org2.ID,
).Error
require.NoError(t, err)
// TODO: Use Orgs.Join to replace SQL hack when the method is available.
err = s.db.Exec(`INSERT INTO org_user (uid, org_id, is_public) VALUES (?, ?, ?)`, alice.ID, org1.ID, false).Error
require.NoError(t, err)
err = s.db.Exec(`INSERT INTO org_user (uid, org_id, is_public) VALUES (?, ?, ?)`, alice.ID, org2.ID, true).Error
require.NoError(t, err)
err = s.db.Exec(`INSERT INTO org_user (uid, org_id, is_public) VALUES (?, ?, ?)`, bob.ID, org2.ID, true).Error
require.NoError(t, err)
tests := []struct {
name string
opts ListOrgsOptions
wantOrgNames []string
}{
{
name: "only public memberships for a user",
opts: ListOrgsOptions{
MemberID: alice.ID,
IncludePrivateMembers: false,
},
wantOrgNames: []string{org2.Name},
},
{
name: "all memberships for a user",
opts: ListOrgsOptions{
MemberID: alice.ID,
IncludePrivateMembers: true,
},
wantOrgNames: []string{org1.Name, org2.Name},
},
{
name: "no membership for a non-existent user",
opts: ListOrgsOptions{
MemberID: 404,
IncludePrivateMembers: true,
},
wantOrgNames: []string{},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
got, err := s.List(ctx, test.opts)
require.NoError(t, err)
gotOrgNames := make([]string, len(got))
for i := range got {
gotOrgNames[i] = got[i].Name
}
assert.Equal(t, test.wantOrgNames, gotOrgNames)
})
}
}
func organizationsSearchByName(t *testing.T, ctx context.Context, s *OrganizationsStore) {
// TODO: Use Orgs.Create to replace SQL hack when the method is available.
usersStore := newUsersStore(s.db)
org1, err := usersStore.Create(ctx, "org1", "org1@example.com", CreateUserOptions{FullName: "Acme Corp"})
require.NoError(t, err)
org2, err := usersStore.Create(ctx, "org2", "org2@example.com", CreateUserOptions{FullName: "Acme Corp 2"})
require.NoError(t, err)
err = s.db.Exec(
dbutil.Quote("UPDATE %s SET type = ? WHERE id IN (?, ?)", "user"),
UserTypeOrganization, org1.ID, org2.ID,
).Error
require.NoError(t, err)
t.Run("search for username org1", func(t *testing.T) {
orgs, count, err := s.SearchByName(ctx, "G1", 1, 1, "")
require.NoError(t, err)
require.Len(t, orgs, int(count))
assert.Equal(t, int64(1), count)
assert.Equal(t, org1.ID, orgs[0].ID)
})
t.Run("search for username org2", func(t *testing.T) {
orgs, count, err := s.SearchByName(ctx, "G2", 1, 1, "")
require.NoError(t, err)
require.Len(t, orgs, int(count))
assert.Equal(t, int64(1), count)
assert.Equal(t, org2.ID, orgs[0].ID)
})
t.Run("search for full name acme", func(t *testing.T) {
orgs, count, err := s.SearchByName(ctx, "ACME", 1, 10, "")
require.NoError(t, err)
require.Len(t, orgs, int(count))
assert.Equal(t, int64(2), count)
})
t.Run("search for full name acme ORDER BY id DESC LIMIT 1", func(t *testing.T) {
orgs, count, err := s.SearchByName(ctx, "ACME", 1, 1, "id DESC")
require.NoError(t, err)
require.Len(t, orgs, 1)
assert.Equal(t, int64(2), count)
assert.Equal(t, org2.ID, orgs[0].ID)
})
}
func organizationsCountByUser(t *testing.T, ctx context.Context, s *OrganizationsStore) {
// TODO: Use Orgs.Join to replace SQL hack when the method is available.
err := s.db.Exec(`INSERT INTO org_user (uid, org_id) VALUES (?, ?)`, 1, 1).Error
require.NoError(t, err)
err = s.db.Exec(`INSERT INTO org_user (uid, org_id) VALUES (?, ?)`, 2, 1).Error
require.NoError(t, err)
got, err := s.CountByUser(ctx, 1)
require.NoError(t, err)
assert.Equal(t, int64(1), got)
got, err = s.CountByUser(ctx, 404)
require.NoError(t, err)
assert.Equal(t, int64(0), got)
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/milestone.go | internal/database/milestone.go | // Copyright 2017 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"fmt"
"time"
log "unknwon.dev/clog/v2"
"xorm.io/xorm"
api "github.com/gogs/go-gogs-client"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/errutil"
)
// Milestone represents a milestone of repository.
type Milestone struct {
ID int64
RepoID int64 `xorm:"INDEX"`
Name string
Content string `xorm:"TEXT"`
RenderedContent string `xorm:"-" json:"-" gorm:"-"`
IsClosed bool
NumIssues int
NumClosedIssues int
NumOpenIssues int `xorm:"-" json:"-" gorm:"-"`
Completeness int // Percentage(1-100).
IsOverDue bool `xorm:"-" json:"-" gorm:"-"`
DeadlineString string `xorm:"-" json:"-" gorm:"-"`
Deadline time.Time `xorm:"-" json:"-" gorm:"-"`
DeadlineUnix int64
ClosedDate time.Time `xorm:"-" json:"-" gorm:"-"`
ClosedDateUnix int64
}
func (m *Milestone) BeforeInsert() {
m.DeadlineUnix = m.Deadline.Unix()
}
func (m *Milestone) BeforeUpdate() {
if m.NumIssues > 0 {
m.Completeness = m.NumClosedIssues * 100 / m.NumIssues
} else {
m.Completeness = 0
}
m.DeadlineUnix = m.Deadline.Unix()
m.ClosedDateUnix = m.ClosedDate.Unix()
}
func (m *Milestone) AfterSet(colName string, _ xorm.Cell) {
switch colName {
case "num_closed_issues":
m.NumOpenIssues = m.NumIssues - m.NumClosedIssues
case "deadline_unix":
m.Deadline = time.Unix(m.DeadlineUnix, 0).Local()
if m.Deadline.Year() == 9999 {
return
}
m.DeadlineString = m.Deadline.Format("2006-01-02")
if time.Now().Local().After(m.Deadline) {
m.IsOverDue = true
}
case "closed_date_unix":
m.ClosedDate = time.Unix(m.ClosedDateUnix, 0).Local()
}
}
// State returns string representation of milestone status.
func (m *Milestone) State() api.StateType {
if m.IsClosed {
return api.STATE_CLOSED
}
return api.STATE_OPEN
}
func (m *Milestone) ChangeStatus(isClosed bool) error {
return ChangeMilestoneStatus(m, isClosed)
}
func (m *Milestone) APIFormat() *api.Milestone {
apiMilestone := &api.Milestone{
ID: m.ID,
State: m.State(),
Title: m.Name,
Description: m.Content,
OpenIssues: m.NumOpenIssues,
ClosedIssues: m.NumClosedIssues,
}
if m.IsClosed {
apiMilestone.Closed = &m.ClosedDate
}
if m.Deadline.Year() < 9999 {
apiMilestone.Deadline = &m.Deadline
}
return apiMilestone
}
func (m *Milestone) CountIssues(isClosed, includePulls bool) int64 {
sess := x.Where("milestone_id = ?", m.ID).And("is_closed = ?", isClosed)
if !includePulls {
sess.And("is_pull = ?", false)
}
count, _ := sess.Count(new(Issue))
return count
}
// NewMilestone creates new milestone of repository.
func NewMilestone(m *Milestone) (err error) {
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if _, err = sess.Insert(m); err != nil {
return err
}
if _, err = sess.Exec("UPDATE `repository` SET num_milestones = num_milestones + 1 WHERE id = ?", m.RepoID); err != nil {
return err
}
return sess.Commit()
}
var _ errutil.NotFound = (*ErrMilestoneNotExist)(nil)
type ErrMilestoneNotExist struct {
args map[string]any
}
func IsErrMilestoneNotExist(err error) bool {
_, ok := err.(ErrMilestoneNotExist)
return ok
}
func (err ErrMilestoneNotExist) Error() string {
return fmt.Sprintf("milestone does not exist: %v", err.args)
}
func (ErrMilestoneNotExist) NotFound() bool {
return true
}
func getMilestoneByRepoID(e Engine, repoID, id int64) (*Milestone, error) {
m := &Milestone{
ID: id,
RepoID: repoID,
}
has, err := e.Get(m)
if err != nil {
return nil, err
} else if !has {
return nil, ErrMilestoneNotExist{args: map[string]any{"repoID": repoID, "milestoneID": id}}
}
return m, nil
}
// GetWebhookByRepoID returns the milestone in a repository.
func GetMilestoneByRepoID(repoID, id int64) (*Milestone, error) {
return getMilestoneByRepoID(x, repoID, id)
}
// GetMilestonesByRepoID returns all milestones of a repository.
func GetMilestonesByRepoID(repoID int64) ([]*Milestone, error) {
miles := make([]*Milestone, 0, 10)
return miles, x.Where("repo_id = ?", repoID).Find(&miles)
}
// GetMilestones returns a list of milestones of given repository and status.
func GetMilestones(repoID int64, page int, isClosed bool) ([]*Milestone, error) {
miles := make([]*Milestone, 0, conf.UI.IssuePagingNum)
sess := x.Where("repo_id = ? AND is_closed = ?", repoID, isClosed)
if page > 0 {
sess = sess.Limit(conf.UI.IssuePagingNum, (page-1)*conf.UI.IssuePagingNum)
}
return miles, sess.Find(&miles)
}
func updateMilestone(e Engine, m *Milestone) error {
_, err := e.ID(m.ID).AllCols().Update(m)
return err
}
// UpdateMilestone updates information of given milestone.
func UpdateMilestone(m *Milestone) error {
return updateMilestone(x, m)
}
func countRepoMilestones(e Engine, repoID int64) int64 {
count, _ := e.Where("repo_id=?", repoID).Count(new(Milestone))
return count
}
// CountRepoMilestones returns number of milestones in given repository.
func CountRepoMilestones(repoID int64) int64 {
return countRepoMilestones(x, repoID)
}
func countRepoClosedMilestones(e Engine, repoID int64) int64 {
closed, _ := e.Where("repo_id=? AND is_closed=?", repoID, true).Count(new(Milestone))
return closed
}
// CountRepoClosedMilestones returns number of closed milestones in given repository.
func CountRepoClosedMilestones(repoID int64) int64 {
return countRepoClosedMilestones(x, repoID)
}
// MilestoneStats returns number of open and closed milestones of given repository.
func MilestoneStats(repoID int64) (open, closed int64) {
open, _ = x.Where("repo_id=? AND is_closed=?", repoID, false).Count(new(Milestone))
return open, CountRepoClosedMilestones(repoID)
}
// ChangeMilestoneStatus changes the milestone open/closed status.
// If milestone passes with changed values, those values will be
// updated to database as well.
func ChangeMilestoneStatus(m *Milestone, isClosed bool) (err error) {
repo, err := GetRepositoryByID(m.RepoID)
if err != nil {
return err
}
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
m.IsClosed = isClosed
if err = updateMilestone(sess, m); err != nil {
return err
}
repo.NumMilestones = int(countRepoMilestones(sess, repo.ID))
repo.NumClosedMilestones = int(countRepoClosedMilestones(sess, repo.ID))
if _, err = sess.ID(repo.ID).AllCols().Update(repo); err != nil {
return err
}
return sess.Commit()
}
func changeMilestoneIssueStats(e *xorm.Session, issue *Issue) error {
if issue.MilestoneID == 0 {
return nil
}
m, err := getMilestoneByRepoID(e, issue.RepoID, issue.MilestoneID)
if err != nil {
return err
}
if issue.IsClosed {
m.NumOpenIssues--
m.NumClosedIssues++
} else {
m.NumOpenIssues++
m.NumClosedIssues--
}
return updateMilestone(e, m)
}
// ChangeMilestoneIssueStats updates the open/closed issues counter and progress
// for the milestone associated with the given issue.
func ChangeMilestoneIssueStats(issue *Issue) (err error) {
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if err = changeMilestoneIssueStats(sess, issue); err != nil {
return err
}
return sess.Commit()
}
func changeMilestoneAssign(e *xorm.Session, issue *Issue, oldMilestoneID int64) error {
if oldMilestoneID > 0 {
m, err := getMilestoneByRepoID(e, issue.RepoID, oldMilestoneID)
if err != nil {
return err
}
m.NumIssues--
if issue.IsClosed {
m.NumClosedIssues--
}
if err = updateMilestone(e, m); err != nil {
return err
} else if _, err = e.Exec("UPDATE `issue_user` SET milestone_id = 0 WHERE issue_id = ?", issue.ID); err != nil {
return err
}
issue.Milestone = nil
}
if issue.MilestoneID > 0 {
m, err := getMilestoneByRepoID(e, issue.RepoID, issue.MilestoneID)
if err != nil {
return err
}
m.NumIssues++
if issue.IsClosed {
m.NumClosedIssues++
}
if err = updateMilestone(e, m); err != nil {
return err
} else if _, err = e.Exec("UPDATE `issue_user` SET milestone_id = ? WHERE issue_id = ?", m.ID, issue.ID); err != nil {
return err
}
issue.Milestone = m
}
return updateIssue(e, issue)
}
// ChangeMilestoneAssign changes assignment of milestone for issue.
func ChangeMilestoneAssign(doer *User, issue *Issue, oldMilestoneID int64) (err error) {
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if err = changeMilestoneAssign(sess, issue, oldMilestoneID); err != nil {
return err
}
if err = sess.Commit(); err != nil {
return fmt.Errorf("commit: %v", err)
}
var hookAction api.HookIssueAction
if issue.MilestoneID > 0 {
hookAction = api.HOOK_ISSUE_MILESTONED
} else {
hookAction = api.HOOK_ISSUE_DEMILESTONED
}
if issue.IsPull {
err = issue.PullRequest.LoadIssue()
if err != nil {
log.Error("LoadIssue: %v", err)
return err
}
err = PrepareWebhooks(issue.Repo, HookEventTypePullRequest, &api.PullRequestPayload{
Action: hookAction,
Index: issue.Index,
PullRequest: issue.PullRequest.APIFormat(),
Repository: issue.Repo.APIFormatLegacy(nil),
Sender: doer.APIFormat(),
})
} else {
err = PrepareWebhooks(issue.Repo, HookEventTypeIssues, &api.IssuesPayload{
Action: hookAction,
Index: issue.Index,
Issue: issue.APIFormat(),
Repository: issue.Repo.APIFormatLegacy(nil),
Sender: doer.APIFormat(),
})
}
if err != nil {
log.Error("PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
}
return nil
}
// DeleteMilestoneOfRepoByID deletes a milestone from a repository.
func DeleteMilestoneOfRepoByID(repoID, id int64) error {
m, err := GetMilestoneByRepoID(repoID, id)
if err != nil {
if IsErrMilestoneNotExist(err) {
return nil
}
return err
}
repo, err := GetRepositoryByID(m.RepoID)
if err != nil {
return err
}
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if _, err = sess.ID(m.ID).Delete(new(Milestone)); err != nil {
return err
}
repo.NumMilestones = int(countRepoMilestones(sess, repo.ID))
repo.NumClosedMilestones = int(countRepoClosedMilestones(sess, repo.ID))
if _, err = sess.ID(repo.ID).AllCols().Update(repo); err != nil {
return err
}
if _, err = sess.Exec("UPDATE `issue` SET milestone_id = 0 WHERE milestone_id = ?", m.ID); err != nil {
return err
} else if _, err = sess.Exec("UPDATE `issue_user` SET milestone_id = 0 WHERE milestone_id = ?", m.ID); err != nil {
return err
}
return sess.Commit()
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/access_tokens.go | internal/database/access_tokens.go | // Copyright 2020 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"context"
"fmt"
"time"
"github.com/pkg/errors"
gouuid "github.com/satori/go.uuid"
"gorm.io/gorm"
"gogs.io/gogs/internal/cryptoutil"
"gogs.io/gogs/internal/errutil"
)
// AccessToken is a personal access token.
type AccessToken struct {
ID int64 `gorm:"primarykey"`
UserID int64 `xorm:"uid" gorm:"column:uid;index"`
Name string
Sha1 string `gorm:"type:VARCHAR(40);unique"`
SHA256 string `gorm:"type:VARCHAR(64);unique;not null"`
Created time.Time `gorm:"-" json:"-"`
CreatedUnix int64
Updated time.Time `gorm:"-" json:"-"`
UpdatedUnix int64
HasRecentActivity bool `gorm:"-" json:"-"`
HasUsed bool `gorm:"-" json:"-"`
}
// BeforeCreate implements the GORM create hook.
func (t *AccessToken) BeforeCreate(tx *gorm.DB) error {
if t.CreatedUnix == 0 {
t.CreatedUnix = tx.NowFunc().Unix()
}
return nil
}
// AfterFind implements the GORM query hook.
func (t *AccessToken) AfterFind(tx *gorm.DB) error {
t.Created = time.Unix(t.CreatedUnix, 0).Local()
if t.UpdatedUnix > 0 {
t.Updated = time.Unix(t.UpdatedUnix, 0).Local()
t.HasUsed = t.Updated.After(t.Created)
t.HasRecentActivity = t.Updated.Add(7 * 24 * time.Hour).After(tx.NowFunc())
}
return nil
}
// AccessTokensStore is the storage layer for access tokens.
type AccessTokensStore struct {
db *gorm.DB
}
func newAccessTokensStore(db *gorm.DB) *AccessTokensStore {
return &AccessTokensStore{db: db}
}
type ErrAccessTokenAlreadyExist struct {
args errutil.Args
}
func IsErrAccessTokenAlreadyExist(err error) bool {
return errors.As(err, &ErrAccessTokenAlreadyExist{})
}
func (err ErrAccessTokenAlreadyExist) Error() string {
return fmt.Sprintf("access token already exists: %v", err.args)
}
// Create creates a new access token and persist to database. It returns
// ErrAccessTokenAlreadyExist when an access token with same name already exists
// for the user.
func (s *AccessTokensStore) Create(ctx context.Context, userID int64, name string) (*AccessToken, error) {
err := s.db.WithContext(ctx).Where("uid = ? AND name = ?", userID, name).First(new(AccessToken)).Error
if err == nil {
return nil, ErrAccessTokenAlreadyExist{args: errutil.Args{"userID": userID, "name": name}}
} else if !errors.Is(err, gorm.ErrRecordNotFound) {
return nil, err
}
token := cryptoutil.SHA1(gouuid.NewV4().String())
sha256 := cryptoutil.SHA256(token)
accessToken := &AccessToken{
UserID: userID,
Name: name,
Sha1: sha256[:40], // To pass the column unique constraint, keep the length of SHA1.
SHA256: sha256,
}
if err = s.db.WithContext(ctx).Create(accessToken).Error; err != nil {
return nil, err
}
// Set back the raw access token value, for the sake of the caller.
accessToken.Sha1 = token
return accessToken, nil
}
// DeleteByID deletes the access token by given ID.
//
// 🚨 SECURITY: The "userID" is required to prevent attacker deletes arbitrary
// access token that belongs to another user.
func (s *AccessTokensStore) DeleteByID(ctx context.Context, userID, id int64) error {
return s.db.WithContext(ctx).Where("id = ? AND uid = ?", id, userID).Delete(new(AccessToken)).Error
}
var _ errutil.NotFound = (*ErrAccessTokenNotExist)(nil)
type ErrAccessTokenNotExist struct {
args errutil.Args
}
// IsErrAccessTokenNotExist returns true if the underlying error has the type
// ErrAccessTokenNotExist.
func IsErrAccessTokenNotExist(err error) bool {
return errors.As(errors.Cause(err), &ErrAccessTokenNotExist{})
}
func (err ErrAccessTokenNotExist) Error() string {
return fmt.Sprintf("access token does not exist: %v", err.args)
}
func (ErrAccessTokenNotExist) NotFound() bool {
return true
}
// GetBySHA1 returns the access token with given SHA1. It returns
// ErrAccessTokenNotExist when not found.
func (s *AccessTokensStore) GetBySHA1(ctx context.Context, sha1 string) (*AccessToken, error) {
// No need to waste a query for an empty SHA1.
if sha1 == "" {
return nil, ErrAccessTokenNotExist{args: errutil.Args{"sha": sha1}}
}
sha256 := cryptoutil.SHA256(sha1)
token := new(AccessToken)
err := s.db.WithContext(ctx).Where("sha256 = ?", sha256).First(token).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrAccessTokenNotExist{args: errutil.Args{"sha": sha1}}
} else if err != nil {
return nil, err
}
return token, nil
}
// List returns all access tokens belongs to given user.
func (s *AccessTokensStore) List(ctx context.Context, userID int64) ([]*AccessToken, error) {
var tokens []*AccessToken
return tokens, s.db.WithContext(ctx).Where("uid = ?", userID).Order("id ASC").Find(&tokens).Error
}
// Touch updates the updated time of the given access token to the current time.
func (s *AccessTokensStore) Touch(ctx context.Context, id int64) error {
return s.db.WithContext(ctx).
Model(new(AccessToken)).
Where("id = ?", id).
UpdateColumn("updated_unix", s.db.NowFunc().Unix()).
Error
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/lfs_test.go | internal/database/lfs_test.go | // Copyright 2020 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gogs.io/gogs/internal/errutil"
"gogs.io/gogs/internal/lfsutil"
)
func TestLFS(t *testing.T) {
if testing.Short() {
t.Skip()
}
t.Parallel()
ctx := context.Background()
s := &LFSStore{
db: newTestDB(t, "LFSStore"),
}
for _, tc := range []struct {
name string
test func(t *testing.T, ctx context.Context, s *LFSStore)
}{
{"CreateObject", lfsCreateObject},
{"GetObjectByOID", lfsGetObjectByOID},
{"GetObjectsByOIDs", lfsGetObjectsByOIDs},
} {
t.Run(tc.name, func(t *testing.T) {
t.Cleanup(func() {
err := clearTables(t, s.db)
require.NoError(t, err)
})
tc.test(t, ctx, s)
})
if t.Failed() {
break
}
}
}
func lfsCreateObject(t *testing.T, ctx context.Context, s *LFSStore) {
// Create first LFS object
repoID := int64(1)
oid := lfsutil.OID("ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f")
err := s.CreateObject(ctx, repoID, oid, 12, lfsutil.StorageLocal)
require.NoError(t, err)
// Get it back and check the CreatedAt field
object, err := s.GetObjectByOID(ctx, repoID, oid)
require.NoError(t, err)
assert.Equal(t, s.db.NowFunc().Format(time.RFC3339), object.CreatedAt.UTC().Format(time.RFC3339))
// Try to create second LFS object with same oid should fail
err = s.CreateObject(ctx, repoID, oid, 12, lfsutil.StorageLocal)
assert.Error(t, err)
}
func lfsGetObjectByOID(t *testing.T, ctx context.Context, s *LFSStore) {
// Create a LFS object
repoID := int64(1)
oid := lfsutil.OID("ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f")
err := s.CreateObject(ctx, repoID, oid, 12, lfsutil.StorageLocal)
require.NoError(t, err)
// We should be able to get it back
_, err = s.GetObjectByOID(ctx, repoID, oid)
require.NoError(t, err)
// Try to get a non-existent object
_, err = s.GetObjectByOID(ctx, repoID, "bad_oid")
expErr := ErrLFSObjectNotExist{args: errutil.Args{"repoID": repoID, "oid": lfsutil.OID("bad_oid")}}
assert.Equal(t, expErr, err)
}
func lfsGetObjectsByOIDs(t *testing.T, ctx context.Context, s *LFSStore) {
// Create two LFS objects
repoID := int64(1)
oid1 := lfsutil.OID("ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f")
oid2 := lfsutil.OID("ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64g")
err := s.CreateObject(ctx, repoID, oid1, 12, lfsutil.StorageLocal)
require.NoError(t, err)
err = s.CreateObject(ctx, repoID, oid2, 12, lfsutil.StorageLocal)
require.NoError(t, err)
// We should be able to get them back and ignore non-existent ones
objects, err := s.GetObjectsByOIDs(ctx, repoID, oid1, oid2, "bad_oid")
require.NoError(t, err)
assert.Equal(t, 2, len(objects), "number of objects")
assert.Equal(t, repoID, objects[0].RepoID)
assert.Equal(t, oid1, objects[0].OID)
assert.Equal(t, repoID, objects[1].RepoID)
assert.Equal(t, oid2, objects[1].OID)
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/models.go | internal/database/models.go | // Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"context"
"database/sql"
"fmt"
"os"
"path"
"path/filepath"
"strings"
"time"
"github.com/pkg/errors"
"gorm.io/gorm"
"gorm.io/gorm/logger"
log "unknwon.dev/clog/v2"
"xorm.io/core"
"xorm.io/xorm"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/database/migrations"
"gogs.io/gogs/internal/dbutil"
)
// Engine represents a XORM engine or session.
type Engine interface {
Delete(any) (int64, error)
Exec(...any) (sql.Result, error)
Find(any, ...any) error
Get(any) (bool, error)
ID(any) *xorm.Session
In(string, ...any) *xorm.Session
Insert(...any) (int64, error)
InsertOne(any) (int64, error)
Iterate(any, xorm.IterFunc) error
Sql(string, ...any) *xorm.Session
Table(any) *xorm.Session
Where(any, ...any) *xorm.Session
}
var (
x *xorm.Engine
legacyTables []any
HasEngine bool
)
func init() {
legacyTables = append(legacyTables,
new(User), new(PublicKey), new(TwoFactor), new(TwoFactorRecoveryCode),
new(Repository), new(DeployKey), new(Collaboration), new(Upload),
new(Watch), new(Star),
new(Issue), new(PullRequest), new(Comment), new(Attachment), new(IssueUser),
new(Label), new(IssueLabel), new(Milestone),
new(Mirror), new(Release), new(Webhook), new(HookTask),
new(ProtectBranch), new(ProtectBranchWhitelist),
new(Team), new(OrgUser), new(TeamUser), new(TeamRepo),
)
gonicNames := []string{"SSL"}
for _, name := range gonicNames {
core.LintGonicMapper[name] = true
}
}
func getEngine() (*xorm.Engine, error) {
Param := "?"
if strings.Contains(conf.Database.Name, Param) {
Param = "&"
}
driver := conf.Database.Type
connStr := ""
switch conf.Database.Type {
case "mysql":
conf.UseMySQL = true
if conf.Database.Host[0] == '/' { // looks like a unix socket
connStr = fmt.Sprintf("%s:%s@unix(%s)/%s%scharset=utf8mb4&parseTime=true",
conf.Database.User, conf.Database.Password, conf.Database.Host, conf.Database.Name, Param)
} else {
connStr = fmt.Sprintf("%s:%s@tcp(%s)/%s%scharset=utf8mb4&parseTime=true",
conf.Database.User, conf.Database.Password, conf.Database.Host, conf.Database.Name, Param)
}
engineParams := map[string]string{"rowFormat": "DYNAMIC"}
return xorm.NewEngineWithParams(conf.Database.Type, connStr, engineParams)
case "postgres":
conf.UsePostgreSQL = true
host, port := dbutil.ParsePostgreSQLHostPort(conf.Database.Host)
connStr = fmt.Sprintf("user='%s' password='%s' host='%s' port='%s' dbname='%s' sslmode='%s' search_path='%s'",
conf.Database.User, conf.Database.Password, host, port, conf.Database.Name, conf.Database.SSLMode, conf.Database.Schema)
driver = "pgx"
case "mssql":
conf.UseMSSQL = true
host, port := dbutil.ParseMSSQLHostPort(conf.Database.Host)
connStr = fmt.Sprintf("server=%s; port=%s; database=%s; user id=%s; password=%s;", host, port, conf.Database.Name, conf.Database.User, conf.Database.Password)
case "sqlite3":
if err := os.MkdirAll(path.Dir(conf.Database.Path), os.ModePerm); err != nil {
return nil, fmt.Errorf("create directories: %v", err)
}
conf.UseSQLite3 = true
connStr = "file:" + conf.Database.Path + "?cache=shared&mode=rwc"
default:
return nil, fmt.Errorf("unknown database type: %s", conf.Database.Type)
}
return xorm.NewEngine(driver, connStr)
}
func NewTestEngine() error {
x, err := getEngine()
if err != nil {
return fmt.Errorf("connect to database: %v", err)
}
if conf.UsePostgreSQL {
x.SetSchema(conf.Database.Schema)
}
x.SetMapper(core.GonicMapper{})
return x.StoreEngine("InnoDB").Sync2(legacyTables...)
}
func SetEngine() (*gorm.DB, error) {
var err error
x, err = getEngine()
if err != nil {
return nil, fmt.Errorf("connect to database: %v", err)
}
if conf.UsePostgreSQL {
x.SetSchema(conf.Database.Schema)
}
x.SetMapper(core.GonicMapper{})
var logPath string
if conf.HookMode {
logPath = filepath.Join(conf.Log.RootPath, "hooks", "xorm.log")
} else {
logPath = filepath.Join(conf.Log.RootPath, "xorm.log")
}
sec := conf.File.Section("log.xorm")
fileWriter, err := log.NewFileWriter(logPath,
log.FileRotationConfig{
Rotate: sec.Key("ROTATE").MustBool(true),
Daily: sec.Key("ROTATE_DAILY").MustBool(true),
MaxSize: sec.Key("MAX_SIZE").MustInt64(100) * 1024 * 1024,
MaxDays: sec.Key("MAX_DAYS").MustInt64(3),
},
)
if err != nil {
return nil, fmt.Errorf("create 'xorm.log': %v", err)
}
x.SetMaxOpenConns(conf.Database.MaxOpenConns)
x.SetMaxIdleConns(conf.Database.MaxIdleConns)
x.SetConnMaxLifetime(time.Second)
if conf.IsProdMode() {
x.SetLogger(xorm.NewSimpleLogger3(fileWriter, xorm.DEFAULT_LOG_PREFIX, xorm.DEFAULT_LOG_FLAG, core.LOG_ERR))
} else {
x.SetLogger(xorm.NewSimpleLogger(fileWriter))
}
x.ShowSQL(true)
var gormLogger logger.Writer
if conf.HookMode {
gormLogger = &dbutil.Logger{Writer: fileWriter}
} else {
gormLogger, err = newLogWriter()
if err != nil {
return nil, errors.Wrap(err, "new log writer")
}
}
return NewConnection(gormLogger)
}
func NewEngine() error {
db, err := SetEngine()
if err != nil {
return err
}
if err = migrations.Migrate(db); err != nil {
return fmt.Errorf("migrate: %v", err)
}
if err = x.StoreEngine("InnoDB").Sync2(legacyTables...); err != nil {
return errors.Wrap(err, "sync tables")
}
return nil
}
type Statistic struct {
Counter struct {
User, Org, PublicKey,
Repo, Watch, Star, Action, Access,
Issue, Comment, Oauth, Follow,
Mirror, Release, LoginSource, Webhook,
Milestone, Label, HookTask,
Team, UpdateTask, Attachment int64
}
}
func GetStatistic(ctx context.Context) (stats Statistic) {
stats.Counter.User = Handle.Users().Count(ctx)
stats.Counter.Org = CountOrganizations()
stats.Counter.PublicKey, _ = x.Count(new(PublicKey))
stats.Counter.Repo = CountRepositories(true)
stats.Counter.Watch, _ = x.Count(new(Watch))
stats.Counter.Star, _ = x.Count(new(Star))
stats.Counter.Action, _ = x.Count(new(Action))
stats.Counter.Access, _ = x.Count(new(Access))
stats.Counter.Issue, _ = x.Count(new(Issue))
stats.Counter.Comment, _ = x.Count(new(Comment))
stats.Counter.Oauth = 0
stats.Counter.Follow, _ = x.Count(new(Follow))
stats.Counter.Mirror, _ = x.Count(new(Mirror))
stats.Counter.Release, _ = x.Count(new(Release))
stats.Counter.LoginSource = Handle.LoginSources().Count(ctx)
stats.Counter.Webhook, _ = x.Count(new(Webhook))
stats.Counter.Milestone, _ = x.Count(new(Milestone))
stats.Counter.Label, _ = x.Count(new(Label))
stats.Counter.HookTask, _ = x.Count(new(HookTask))
stats.Counter.Team, _ = x.Count(new(Team))
stats.Counter.Attachment, _ = x.Count(new(Attachment))
return stats
}
func Ping() error {
if x == nil {
return errors.New("database not available")
}
return x.Ping()
}
// The version table. Should have only one row with id==1
type Version struct {
ID int64
Version int64
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/repo_tag.go | internal/database/repo_tag.go | // Copyright 2021 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"fmt"
"github.com/gogs/git-module"
)
type Tag struct {
RepoPath string
Name string
IsProtected bool
Commit *git.Commit
}
func (ta *Tag) GetCommit() (*git.Commit, error) {
gitRepo, err := git.Open(ta.RepoPath)
if err != nil {
return nil, fmt.Errorf("open repository: %v", err)
}
return gitRepo.TagCommit(ta.Name)
}
func GetTagsByPath(path string) ([]*Tag, error) {
gitRepo, err := git.Open(path)
if err != nil {
return nil, fmt.Errorf("open repository: %v", err)
}
names, err := gitRepo.Tags()
if err != nil {
return nil, fmt.Errorf("list tags")
}
tags := make([]*Tag, len(names))
for i := range names {
tags[i] = &Tag{
RepoPath: path,
Name: names[i],
}
}
return tags, nil
}
func (r *Repository) GetTags() ([]*Tag, error) {
return GetTagsByPath(r.RepoPath())
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/webhook.go | internal/database/webhook.go | // Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"crypto/hmac"
"crypto/sha256"
"crypto/tls"
"encoding/hex"
"fmt"
"io"
"net/url"
"strings"
"time"
jsoniter "github.com/json-iterator/go"
gouuid "github.com/satori/go.uuid"
log "unknwon.dev/clog/v2"
"xorm.io/xorm"
api "github.com/gogs/go-gogs-client"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/errutil"
"gogs.io/gogs/internal/httplib"
"gogs.io/gogs/internal/netutil"
"gogs.io/gogs/internal/sync"
"gogs.io/gogs/internal/testutil"
)
var HookQueue = sync.NewUniqueQueue(1000)
type HookContentType int
const (
JSON HookContentType = iota + 1
FORM
)
var hookContentTypes = map[string]HookContentType{
"json": JSON,
"form": FORM,
}
// ToHookContentType returns HookContentType by given name.
func ToHookContentType(name string) HookContentType {
return hookContentTypes[name]
}
func (t HookContentType) Name() string {
switch t {
case JSON:
return "json"
case FORM:
return "form"
}
return ""
}
// IsValidHookContentType returns true if given name is a valid hook content type.
func IsValidHookContentType(name string) bool {
_, ok := hookContentTypes[name]
return ok
}
type HookEvents struct {
Create bool `json:"create"`
Delete bool `json:"delete"`
Fork bool `json:"fork"`
Push bool `json:"push"`
Issues bool `json:"issues"`
PullRequest bool `json:"pull_request"`
IssueComment bool `json:"issue_comment"`
Release bool `json:"release"`
}
// HookEvent represents events that will delivery hook.
type HookEvent struct {
PushOnly bool `json:"push_only"`
SendEverything bool `json:"send_everything"`
ChooseEvents bool `json:"choose_events"`
HookEvents `json:"events"`
}
type HookStatus int
const (
HookStatusNone = iota
HookStatusSucceed
HookStatusFailed
)
// Webhook represents a web hook object.
type Webhook struct {
ID int64
RepoID int64
OrgID int64
URL string `xorm:"url TEXT"`
ContentType HookContentType
Secret string `xorm:"TEXT"`
Events string `xorm:"TEXT"`
*HookEvent `xorm:"-"` // LEGACY [1.0]: Cannot ignore JSON (i.e. json:"-") here, it breaks old backup archive
IsSSL bool `xorm:"is_ssl"`
IsActive bool
HookTaskType HookTaskType
Meta string `xorm:"TEXT"` // store hook-specific attributes
LastStatus HookStatus // Last delivery status
Created time.Time `xorm:"-" json:"-" gorm:"-"`
CreatedUnix int64
Updated time.Time `xorm:"-" json:"-" gorm:"-"`
UpdatedUnix int64
}
func (w *Webhook) BeforeInsert() {
w.CreatedUnix = time.Now().Unix()
w.UpdatedUnix = w.CreatedUnix
}
func (w *Webhook) BeforeUpdate() {
w.UpdatedUnix = time.Now().Unix()
}
func (w *Webhook) AfterSet(colName string, _ xorm.Cell) {
var err error
switch colName {
case "events":
w.HookEvent = &HookEvent{}
if err = jsoniter.Unmarshal([]byte(w.Events), w.HookEvent); err != nil {
log.Error("Unmarshal [%d]: %v", w.ID, err)
}
case "created_unix":
w.Created = time.Unix(w.CreatedUnix, 0).Local()
case "updated_unix":
w.Updated = time.Unix(w.UpdatedUnix, 0).Local()
}
}
func (w *Webhook) SlackMeta() *SlackMeta {
s := &SlackMeta{}
if err := jsoniter.Unmarshal([]byte(w.Meta), s); err != nil {
log.Error("Failed to get Slack meta [webhook_id: %d]: %v", w.ID, err)
}
return s
}
// History returns history of webhook by given conditions.
func (w *Webhook) History(page int) ([]*HookTask, error) {
return HookTasks(w.ID, page)
}
// UpdateEvent handles conversion from HookEvent to Events.
func (w *Webhook) UpdateEvent() error {
data, err := jsoniter.Marshal(w.HookEvent)
w.Events = string(data)
return err
}
// HasCreateEvent returns true if hook enabled create event.
func (w *Webhook) HasCreateEvent() bool {
return w.SendEverything ||
(w.ChooseEvents && w.Create)
}
// HasDeleteEvent returns true if hook enabled delete event.
func (w *Webhook) HasDeleteEvent() bool {
return w.SendEverything ||
(w.ChooseEvents && w.Delete)
}
// HasForkEvent returns true if hook enabled fork event.
func (w *Webhook) HasForkEvent() bool {
return w.SendEverything ||
(w.ChooseEvents && w.Fork)
}
// HasPushEvent returns true if hook enabled push event.
func (w *Webhook) HasPushEvent() bool {
return w.PushOnly || w.SendEverything ||
(w.ChooseEvents && w.Push)
}
// HasIssuesEvent returns true if hook enabled issues event.
func (w *Webhook) HasIssuesEvent() bool {
return w.SendEverything ||
(w.ChooseEvents && w.Issues)
}
// HasPullRequestEvent returns true if hook enabled pull request event.
func (w *Webhook) HasPullRequestEvent() bool {
return w.SendEverything ||
(w.ChooseEvents && w.PullRequest)
}
// HasIssueCommentEvent returns true if hook enabled issue comment event.
func (w *Webhook) HasIssueCommentEvent() bool {
return w.SendEverything ||
(w.ChooseEvents && w.IssueComment)
}
// HasReleaseEvent returns true if hook enabled release event.
func (w *Webhook) HasReleaseEvent() bool {
return w.SendEverything ||
(w.ChooseEvents && w.Release)
}
type eventChecker struct {
checker func() bool
typ HookEventType
}
func (w *Webhook) EventsArray() []string {
events := make([]string, 0, 8)
eventCheckers := []eventChecker{
{w.HasCreateEvent, HookEventTypeCreate},
{w.HasDeleteEvent, HookEventTypeDelete},
{w.HasForkEvent, HookEventTypeFork},
{w.HasPushEvent, HookEventTypePush},
{w.HasIssuesEvent, HookEventTypeIssues},
{w.HasPullRequestEvent, HookEventTypePullRequest},
{w.HasIssueCommentEvent, HookEventTypeIssueComment},
{w.HasReleaseEvent, HookEventTypeRelease},
}
for _, c := range eventCheckers {
if c.checker() {
events = append(events, string(c.typ))
}
}
return events
}
// CreateWebhook creates a new web hook.
func CreateWebhook(w *Webhook) error {
_, err := x.Insert(w)
return err
}
var _ errutil.NotFound = (*ErrWebhookNotExist)(nil)
type ErrWebhookNotExist struct {
args map[string]any
}
func IsErrWebhookNotExist(err error) bool {
_, ok := err.(ErrWebhookNotExist)
return ok
}
func (err ErrWebhookNotExist) Error() string {
return fmt.Sprintf("webhook does not exist: %v", err.args)
}
func (ErrWebhookNotExist) NotFound() bool {
return true
}
// getWebhook uses argument bean as query condition,
// ID must be specified and do not assign unnecessary fields.
func getWebhook(bean *Webhook) (*Webhook, error) {
has, err := x.Get(bean)
if err != nil {
return nil, err
} else if !has {
return nil, ErrWebhookNotExist{args: map[string]any{"webhookID": bean.ID}}
}
return bean, nil
}
// GetWebhookByID returns webhook by given ID.
// Use this function with caution of accessing unauthorized webhook,
// which means should only be used in non-user interactive functions.
func GetWebhookByID(id int64) (*Webhook, error) {
return getWebhook(&Webhook{
ID: id,
})
}
// GetWebhookOfRepoByID returns webhook of repository by given ID.
func GetWebhookOfRepoByID(repoID, id int64) (*Webhook, error) {
return getWebhook(&Webhook{
ID: id,
RepoID: repoID,
})
}
// GetWebhookByOrgID returns webhook of organization by given ID.
func GetWebhookByOrgID(orgID, id int64) (*Webhook, error) {
return getWebhook(&Webhook{
ID: id,
OrgID: orgID,
})
}
// getActiveWebhooksByRepoID returns all active webhooks of repository.
func getActiveWebhooksByRepoID(e Engine, repoID int64) ([]*Webhook, error) {
webhooks := make([]*Webhook, 0, 5)
return webhooks, e.Where("repo_id = ?", repoID).And("is_active = ?", true).Find(&webhooks)
}
// GetWebhooksByRepoID returns all webhooks of a repository.
func GetWebhooksByRepoID(repoID int64) ([]*Webhook, error) {
webhooks := make([]*Webhook, 0, 5)
return webhooks, x.Find(&webhooks, &Webhook{RepoID: repoID})
}
// UpdateWebhook updates information of webhook.
func UpdateWebhook(w *Webhook) error {
_, err := x.Id(w.ID).AllCols().Update(w)
return err
}
// deleteWebhook uses argument bean as query condition,
// ID must be specified and do not assign unnecessary fields.
func deleteWebhook(bean *Webhook) (err error) {
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if _, err = sess.Delete(bean); err != nil {
return err
} else if _, err = sess.Delete(&HookTask{HookID: bean.ID}); err != nil {
return err
}
return sess.Commit()
}
// DeleteWebhookOfRepoByID deletes webhook of repository by given ID.
func DeleteWebhookOfRepoByID(repoID, id int64) error {
return deleteWebhook(&Webhook{
ID: id,
RepoID: repoID,
})
}
// DeleteWebhookOfOrgByID deletes webhook of organization by given ID.
func DeleteWebhookOfOrgByID(orgID, id int64) error {
return deleteWebhook(&Webhook{
ID: id,
OrgID: orgID,
})
}
// GetWebhooksByOrgID returns all webhooks for an organization.
func GetWebhooksByOrgID(orgID int64) (ws []*Webhook, err error) {
err = x.Find(&ws, &Webhook{OrgID: orgID})
return ws, err
}
// getActiveWebhooksByOrgID returns all active webhooks for an organization.
func getActiveWebhooksByOrgID(e Engine, orgID int64) ([]*Webhook, error) {
ws := make([]*Webhook, 0, 3)
return ws, e.Where("org_id=?", orgID).And("is_active=?", true).Find(&ws)
}
// ___ ___ __ ___________ __
// / | \ ____ ____ | | _\__ ___/____ _____| | __
// / ~ \/ _ \ / _ \| |/ / | | \__ \ / ___/ |/ /
// \ Y ( <_> | <_> ) < | | / __ \_\___ \| <
// \___|_ / \____/ \____/|__|_ \ |____| (____ /____ >__|_ \
// \/ \/ \/ \/ \/
type HookTaskType int
const (
GOGS HookTaskType = iota + 1
SLACK
DISCORD
DINGTALK
)
var hookTaskTypes = map[string]HookTaskType{
"gogs": GOGS,
"slack": SLACK,
"discord": DISCORD,
"dingtalk": DINGTALK,
}
// ToHookTaskType returns HookTaskType by given name.
func ToHookTaskType(name string) HookTaskType {
return hookTaskTypes[name]
}
func (t HookTaskType) Name() string {
switch t {
case GOGS:
return "gogs"
case SLACK:
return "slack"
case DISCORD:
return "discord"
case DINGTALK:
return "dingtalk"
}
return ""
}
// IsValidHookTaskType returns true if given name is a valid hook task type.
func IsValidHookTaskType(name string) bool {
_, ok := hookTaskTypes[name]
return ok
}
type HookEventType string
const (
HookEventTypeCreate HookEventType = "create"
HookEventTypeDelete HookEventType = "delete"
HookEventTypeFork HookEventType = "fork"
HookEventTypePush HookEventType = "push"
HookEventTypeIssues HookEventType = "issues"
HookEventTypePullRequest HookEventType = "pull_request"
HookEventTypeIssueComment HookEventType = "issue_comment"
HookEventTypeRelease HookEventType = "release"
)
// HookRequest represents hook task request information.
type HookRequest struct {
Headers map[string]string `json:"headers"`
}
// HookResponse represents hook task response information.
type HookResponse struct {
Status int `json:"status"`
Headers map[string]string `json:"headers"`
Body string `json:"body"`
}
// HookTask represents a hook task.
type HookTask struct {
ID int64
RepoID int64 `xorm:"INDEX"`
HookID int64
UUID string
Type HookTaskType
URL string `xorm:"TEXT"`
Signature string `xorm:"TEXT"`
api.Payloader `xorm:"-" json:"-" gorm:"-"`
PayloadContent string `xorm:"TEXT"`
ContentType HookContentType
EventType HookEventType
IsSSL bool
IsDelivered bool
Delivered int64
DeliveredString string `xorm:"-" json:"-" gorm:"-"`
// History info.
IsSucceed bool
RequestContent string `xorm:"TEXT"`
RequestInfo *HookRequest `xorm:"-" json:"-" gorm:"-"`
ResponseContent string `xorm:"TEXT"`
ResponseInfo *HookResponse `xorm:"-" json:"-" gorm:"-"`
}
func (t *HookTask) BeforeUpdate() {
if t.RequestInfo != nil {
t.RequestContent = t.ToJSON(t.RequestInfo)
}
if t.ResponseInfo != nil {
t.ResponseContent = t.ToJSON(t.ResponseInfo)
}
}
func (t *HookTask) AfterSet(colName string, _ xorm.Cell) {
var err error
switch colName {
case "delivered":
t.DeliveredString = time.Unix(0, t.Delivered).Format("2006-01-02 15:04:05 MST")
case "request_content":
if t.RequestContent == "" {
return
}
t.RequestInfo = &HookRequest{}
if err = jsoniter.Unmarshal([]byte(t.RequestContent), t.RequestInfo); err != nil {
log.Error("Unmarshal[%d]: %v", t.ID, err)
}
case "response_content":
if t.ResponseContent == "" {
return
}
t.ResponseInfo = &HookResponse{}
if err = jsoniter.Unmarshal([]byte(t.ResponseContent), t.ResponseInfo); err != nil {
log.Error("Unmarshal [%d]: %v", t.ID, err)
}
}
}
func (t *HookTask) ToJSON(v any) string {
p, err := jsoniter.Marshal(v)
if err != nil {
log.Error("Marshal [%d]: %v", t.ID, err)
}
return string(p)
}
// HookTasks returns a list of hook tasks by given conditions.
func HookTasks(hookID int64, page int) ([]*HookTask, error) {
tasks := make([]*HookTask, 0, conf.Webhook.PagingNum)
return tasks, x.Limit(conf.Webhook.PagingNum, (page-1)*conf.Webhook.PagingNum).Where("hook_id=?", hookID).Desc("id").Find(&tasks)
}
// createHookTask creates a new hook task,
// it handles conversion from Payload to PayloadContent.
func createHookTask(e Engine, t *HookTask) error {
data, err := t.JSONPayload()
if err != nil {
return err
}
t.UUID = gouuid.NewV4().String()
t.PayloadContent = string(data)
_, err = e.Insert(t)
return err
}
var _ errutil.NotFound = (*ErrHookTaskNotExist)(nil)
type ErrHookTaskNotExist struct {
args map[string]any
}
func IsHookTaskNotExist(err error) bool {
_, ok := err.(ErrHookTaskNotExist)
return ok
}
func (err ErrHookTaskNotExist) Error() string {
return fmt.Sprintf("hook task does not exist: %v", err.args)
}
func (ErrHookTaskNotExist) NotFound() bool {
return true
}
// GetHookTaskOfWebhookByUUID returns hook task of given webhook by UUID.
func GetHookTaskOfWebhookByUUID(webhookID int64, uuid string) (*HookTask, error) {
hookTask := &HookTask{
HookID: webhookID,
UUID: uuid,
}
has, err := x.Get(hookTask)
if err != nil {
return nil, err
} else if !has {
return nil, ErrHookTaskNotExist{args: map[string]any{"webhookID": webhookID, "uuid": uuid}}
}
return hookTask, nil
}
// UpdateHookTask updates information of hook task.
func UpdateHookTask(t *HookTask) error {
_, err := x.Id(t.ID).AllCols().Update(t)
return err
}
// prepareHookTasks adds list of webhooks to task queue.
func prepareHookTasks(e Engine, repo *Repository, event HookEventType, p api.Payloader, webhooks []*Webhook) (err error) {
if len(webhooks) == 0 {
return nil
}
var payloader api.Payloader
for _, w := range webhooks {
switch event {
case HookEventTypeCreate:
if !w.HasCreateEvent() {
continue
}
case HookEventTypeDelete:
if !w.HasDeleteEvent() {
continue
}
case HookEventTypeFork:
if !w.HasForkEvent() {
continue
}
case HookEventTypePush:
if !w.HasPushEvent() {
continue
}
case HookEventTypeIssues:
if !w.HasIssuesEvent() {
continue
}
case HookEventTypePullRequest:
if !w.HasPullRequestEvent() {
continue
}
case HookEventTypeIssueComment:
if !w.HasIssueCommentEvent() {
continue
}
case HookEventTypeRelease:
if !w.HasReleaseEvent() {
continue
}
}
// Use separate objects so modifications won't be made on payload on non-Gogs type hooks.
switch w.HookTaskType {
case SLACK:
payloader, err = GetSlackPayload(p, event, w.Meta)
if err != nil {
return fmt.Errorf("GetSlackPayload: %v", err)
}
case DISCORD:
payloader, err = GetDiscordPayload(p, event, w.Meta)
if err != nil {
return fmt.Errorf("GetDiscordPayload: %v", err)
}
case DINGTALK:
payloader, err = GetDingtalkPayload(p, event)
if err != nil {
return fmt.Errorf("GetDingtalkPayload: %v", err)
}
default:
payloader = p
}
var signature string
if len(w.Secret) > 0 {
data, err := payloader.JSONPayload()
if err != nil {
log.Error("prepareWebhooks.JSONPayload: %v", err)
}
sig := hmac.New(sha256.New, []byte(w.Secret))
_, _ = sig.Write(data)
signature = hex.EncodeToString(sig.Sum(nil))
}
if err = createHookTask(e, &HookTask{
RepoID: repo.ID,
HookID: w.ID,
Type: w.HookTaskType,
URL: w.URL,
Signature: signature,
Payloader: payloader,
ContentType: w.ContentType,
EventType: event,
IsSSL: w.IsSSL,
}); err != nil {
return fmt.Errorf("createHookTask: %v", err)
}
}
// It's safe to fail when the whole function is called during hook execution
// because resource released after exit. Also, there is no process started to
// consume this input during hook execution.
go HookQueue.Add(repo.ID)
return nil
}
func prepareWebhooks(e Engine, repo *Repository, event HookEventType, p api.Payloader) error {
webhooks, err := getActiveWebhooksByRepoID(e, repo.ID)
if err != nil {
return fmt.Errorf("getActiveWebhooksByRepoID [%d]: %v", repo.ID, err)
}
// check if repo belongs to org and append additional webhooks
if repo.mustOwner(e).IsOrganization() {
// get hooks for org
orgws, err := getActiveWebhooksByOrgID(e, repo.OwnerID)
if err != nil {
return fmt.Errorf("getActiveWebhooksByOrgID [%d]: %v", repo.OwnerID, err)
}
webhooks = append(webhooks, orgws...)
}
return prepareHookTasks(e, repo, event, p, webhooks)
}
// PrepareWebhooks adds all active webhooks to task queue.
func PrepareWebhooks(repo *Repository, event HookEventType, p api.Payloader) error {
// NOTE: To prevent too many cascading changes in a single refactoring PR, we
// choose to ignore this function in tests.
if x == nil && testutil.InTest {
return nil
}
return prepareWebhooks(x, repo, event, p)
}
// TestWebhook adds the test webhook matches the ID to task queue.
func TestWebhook(repo *Repository, event HookEventType, p api.Payloader, webhookID int64) error {
webhook, err := GetWebhookOfRepoByID(repo.ID, webhookID)
if err != nil {
return fmt.Errorf("GetWebhookOfRepoByID [repo_id: %d, id: %d]: %v", repo.ID, webhookID, err)
}
return prepareHookTasks(x, repo, event, p, []*Webhook{webhook})
}
func (t *HookTask) deliver() {
payloadURL, err := url.Parse(t.URL)
if err != nil {
t.ResponseContent = fmt.Sprintf(`{"body": "Cannot parse payload URL: %v"}`, err)
return
}
if netutil.IsBlockedLocalHostname(payloadURL.Hostname(), conf.Security.LocalNetworkAllowlist) {
t.ResponseContent = `{"body": "Payload URL resolved to a local network address that is implicitly blocked."}`
return
}
t.IsDelivered = true
timeout := time.Duration(conf.Webhook.DeliverTimeout) * time.Second
req := httplib.Post(t.URL).SetTimeout(timeout, timeout).
Header("X-Github-Delivery", t.UUID).
Header("X-Github-Event", string(t.EventType)).
Header("X-Gogs-Delivery", t.UUID).
Header("X-Gogs-Signature", t.Signature).
Header("X-Gogs-Event", string(t.EventType)).
SetTLSClientConfig(&tls.Config{InsecureSkipVerify: conf.Webhook.SkipTLSVerify})
switch t.ContentType {
case JSON:
req = req.Header("Content-Type", "application/json").Body(t.PayloadContent)
case FORM:
req.Param("payload", t.PayloadContent)
}
// Record delivery information.
t.RequestInfo = &HookRequest{
Headers: map[string]string{},
}
for k, vals := range req.Headers() {
t.RequestInfo.Headers[k] = strings.Join(vals, ",")
}
t.ResponseInfo = &HookResponse{
Headers: map[string]string{},
}
defer func() {
t.Delivered = time.Now().UnixNano()
if t.IsSucceed {
log.Trace("Hook delivered: %s", t.UUID)
} else {
log.Trace("Hook delivery failed: %s", t.UUID)
}
// Update webhook last delivery status.
w, err := GetWebhookByID(t.HookID)
if err != nil {
log.Error("GetWebhookByID: %v", err)
return
}
if t.IsSucceed {
w.LastStatus = HookStatusSucceed
} else {
w.LastStatus = HookStatusFailed
}
if err = UpdateWebhook(w); err != nil {
log.Error("UpdateWebhook: %v", err)
return
}
}()
resp, err := req.Response()
if err != nil {
t.ResponseInfo.Body = fmt.Sprintf("Delivery: %v", err)
return
}
defer resp.Body.Close()
// Status code is 20x can be seen as succeed.
t.IsSucceed = resp.StatusCode/100 == 2
t.ResponseInfo.Status = resp.StatusCode
for k, vals := range resp.Header {
t.ResponseInfo.Headers[k] = strings.Join(vals, ",")
}
p, err := io.ReadAll(resp.Body)
if err != nil {
t.ResponseInfo.Body = fmt.Sprintf("read body: %s", err)
return
}
t.ResponseInfo.Body = string(p)
}
// DeliverHooks checks and delivers undelivered hooks.
// TODO: shoot more hooks at same time.
func DeliverHooks() {
tasks := make([]*HookTask, 0, 10)
_ = x.Where("is_delivered = ?", false).Iterate(new(HookTask),
func(idx int, bean any) error {
t := bean.(*HookTask)
t.deliver()
tasks = append(tasks, t)
return nil
})
// Update hook task status.
for _, t := range tasks {
if err := UpdateHookTask(t); err != nil {
log.Error("UpdateHookTask [%d]: %v", t.ID, err)
}
}
// Start listening on new hook requests.
for repoID := range HookQueue.Queue() {
log.Trace("DeliverHooks [repo_id: %v]", repoID)
HookQueue.Remove(repoID)
tasks = make([]*HookTask, 0, 5)
if err := x.Where("repo_id = ?", repoID).And("is_delivered = ?", false).Find(&tasks); err != nil {
log.Error("Get repository [%s] hook tasks: %v", repoID, err)
continue
}
for _, t := range tasks {
t.deliver()
if err := UpdateHookTask(t); err != nil {
log.Error("UpdateHookTask [%d]: %v", t.ID, err)
continue
}
}
}
}
func InitDeliverHooks() {
go DeliverHooks()
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/mirror.go | internal/database/mirror.go | // Copyright 2016 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"context"
"fmt"
"net/url"
"strings"
"time"
"github.com/unknwon/com"
"gopkg.in/ini.v1"
log "unknwon.dev/clog/v2"
"xorm.io/xorm"
"github.com/gogs/git-module"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/database/errors"
"gogs.io/gogs/internal/process"
"gogs.io/gogs/internal/sync"
)
var MirrorQueue = sync.NewUniqueQueue(1000)
// Mirror represents mirror information of a repository.
type Mirror struct {
ID int64
RepoID int64
Repo *Repository `xorm:"-" json:"-" gorm:"-"`
Interval int // Hour.
EnablePrune bool `xorm:"NOT NULL DEFAULT true"`
// Last and next sync time of Git data from upstream
LastSync time.Time `xorm:"-" json:"-" gorm:"-"`
LastSyncUnix int64 `xorm:"updated_unix"`
NextSync time.Time `xorm:"-" json:"-" gorm:"-"`
NextSyncUnix int64 `xorm:"next_update_unix"`
address string `xorm:"-"`
}
func (m *Mirror) BeforeInsert() {
m.NextSyncUnix = m.NextSync.Unix()
}
func (m *Mirror) BeforeUpdate() {
m.LastSyncUnix = m.LastSync.Unix()
m.NextSyncUnix = m.NextSync.Unix()
}
func (m *Mirror) AfterSet(colName string, _ xorm.Cell) {
var err error
switch colName {
case "repo_id":
m.Repo, err = GetRepositoryByID(m.RepoID)
if err != nil {
log.Error("GetRepositoryByID [%d]: %v", m.ID, err)
}
case "updated_unix":
m.LastSync = time.Unix(m.LastSyncUnix, 0).Local()
case "next_update_unix":
m.NextSync = time.Unix(m.NextSyncUnix, 0).Local()
}
}
// ScheduleNextSync calculates and sets next sync time based on repository mirror setting.
func (m *Mirror) ScheduleNextSync() {
m.NextSync = time.Now().Add(time.Duration(m.Interval) * time.Hour)
}
func (m *Mirror) readAddress() {
if len(m.address) > 0 {
return
}
cfg, err := ini.LoadSources(
ini.LoadOptions{IgnoreInlineComment: true},
m.Repo.GitConfigPath(),
)
if err != nil {
log.Error("load config: %v", err)
return
}
m.address = cfg.Section("remote \"origin\"").Key("url").Value()
}
// HandleMirrorCredentials replaces user credentials from HTTP/HTTPS URL
// with placeholder <credentials>.
// It returns original string if protocol is not HTTP/HTTPS.
// TODO(unknwon): Use url.Parse.
func HandleMirrorCredentials(url string, mosaics bool) string {
i := strings.Index(url, "@")
if i == -1 {
return url
}
start := strings.Index(url, "://")
if start == -1 {
return url
}
if mosaics {
return url[:start+3] + "<credentials>" + url[i:]
}
return url[:start+3] + url[i+1:]
}
// Address returns mirror address from Git repository config without credentials.
func (m *Mirror) Address() string {
m.readAddress()
return HandleMirrorCredentials(m.address, false)
}
// MosaicsAddress returns mirror address from Git repository config with credentials under mosaics.
func (m *Mirror) MosaicsAddress() string {
m.readAddress()
return HandleMirrorCredentials(m.address, true)
}
// RawAddress returns raw mirror address directly from Git repository config.
func (m *Mirror) RawAddress() string {
m.readAddress()
return m.address
}
// SaveAddress writes new address to Git repository config.
func (m *Mirror) SaveAddress(addr string) error {
repoPath := m.Repo.RepoPath()
err := git.RemoteRemove(repoPath, "origin")
if err != nil {
return fmt.Errorf("remove remote 'origin': %v", err)
}
addrURL, err := url.Parse(addr)
if err != nil {
return err
}
err = git.RemoteAdd(repoPath, "origin", addrURL.String(), git.RemoteAddOptions{MirrorFetch: true})
if err != nil {
return fmt.Errorf("add remote 'origin': %v", err)
}
return nil
}
const gitShortEmptyID = "0000000"
// mirrorSyncResult contains information of a updated reference.
// If the oldCommitID is "0000000", it means a new reference, the value of newCommitID is empty.
// If the newCommitID is "0000000", it means the reference is deleted, the value of oldCommitID is empty.
type mirrorSyncResult struct {
refName string
oldCommitID string
newCommitID string
}
// parseRemoteUpdateOutput detects create, update and delete operations of references from upstream.
func parseRemoteUpdateOutput(output string) []*mirrorSyncResult {
results := make([]*mirrorSyncResult, 0, 3)
lines := strings.Split(output, "\n")
for i := range lines {
// Make sure reference name is presented before continue
idx := strings.Index(lines[i], "-> ")
if idx == -1 {
continue
}
refName := lines[i][idx+3:]
switch {
case strings.HasPrefix(lines[i], " * "): // New reference
results = append(results, &mirrorSyncResult{
refName: refName,
oldCommitID: gitShortEmptyID,
})
case strings.HasPrefix(lines[i], " - "): // Delete reference
results = append(results, &mirrorSyncResult{
refName: refName,
newCommitID: gitShortEmptyID,
})
case strings.HasPrefix(lines[i], " "): // New commits of a reference
delimIdx := strings.Index(lines[i][3:], " ")
if delimIdx == -1 {
log.Error("SHA delimiter not found: %q", lines[i])
continue
}
shas := strings.Split(lines[i][3:delimIdx+3], "..")
if len(shas) != 2 {
log.Error("Expect two SHAs but not what found: %q", lines[i])
continue
}
results = append(results, &mirrorSyncResult{
refName: refName,
oldCommitID: shas[0],
newCommitID: shas[1],
})
default:
log.Warn("parseRemoteUpdateOutput: unexpected update line %q", lines[i])
}
}
return results
}
// runSync returns true if sync finished without error.
func (m *Mirror) runSync() ([]*mirrorSyncResult, bool) {
repoPath := m.Repo.RepoPath()
wikiPath := m.Repo.WikiPath()
timeout := time.Duration(conf.Git.Timeout.Mirror) * time.Second
// Do a fast-fail testing against on repository URL to ensure it is accessible under
// good condition to prevent long blocking on URL resolution without syncing anything.
if !git.IsURLAccessible(time.Minute, m.RawAddress()) {
desc := fmt.Sprintf("Source URL of mirror repository '%s' is not accessible: %s", m.Repo.FullName(), m.MosaicsAddress())
if err := Handle.Notices().Create(context.TODO(), NoticeTypeRepository, desc); err != nil {
log.Error("CreateRepositoryNotice: %v", err)
}
return nil, false
}
gitArgs := []string{"remote", "update"}
if m.EnablePrune {
gitArgs = append(gitArgs, "--prune")
}
_, stderr, err := process.ExecDir(
timeout, repoPath, fmt.Sprintf("Mirror.runSync: %s", repoPath),
"git", gitArgs...)
if err != nil {
const fmtStr = "Failed to update mirror repository %q: %s"
log.Error(fmtStr, repoPath, stderr)
if err = Handle.Notices().Create(
context.TODO(),
NoticeTypeRepository,
fmt.Sprintf(fmtStr, repoPath, stderr),
); err != nil {
log.Error("CreateRepositoryNotice: %v", err)
}
return nil, false
}
output := stderr
if err := m.Repo.UpdateSize(); err != nil {
log.Error("UpdateSize [repo_id: %d]: %v", m.Repo.ID, err)
}
if m.Repo.HasWiki() {
// Even if wiki sync failed, we still want results from the main repository
if _, stderr, err := process.ExecDir(
timeout, wikiPath, fmt.Sprintf("Mirror.runSync: %s", wikiPath),
"git", "remote", "update", "--prune"); err != nil {
const fmtStr = "Failed to update mirror wiki repository %q: %s"
log.Error(fmtStr, wikiPath, stderr)
if err = Handle.Notices().Create(
context.TODO(),
NoticeTypeRepository,
fmt.Sprintf(fmtStr, wikiPath, stderr),
); err != nil {
log.Error("CreateRepositoryNotice: %v", err)
}
}
}
return parseRemoteUpdateOutput(output), true
}
func getMirrorByRepoID(e Engine, repoID int64) (*Mirror, error) {
m := &Mirror{RepoID: repoID}
has, err := e.Get(m)
if err != nil {
return nil, err
} else if !has {
return nil, errors.MirrorNotExist{RepoID: repoID}
}
return m, nil
}
// GetMirrorByRepoID returns mirror information of a repository.
func GetMirrorByRepoID(repoID int64) (*Mirror, error) {
return getMirrorByRepoID(x, repoID)
}
func updateMirror(e Engine, m *Mirror) error {
_, err := e.ID(m.ID).AllCols().Update(m)
return err
}
func UpdateMirror(m *Mirror) error {
return updateMirror(x, m)
}
func DeleteMirrorByRepoID(repoID int64) error {
_, err := x.Delete(&Mirror{RepoID: repoID})
return err
}
// MirrorUpdate checks and updates mirror repositories.
func MirrorUpdate() {
if taskStatusTable.IsRunning(taskNameMirrorUpdate) {
return
}
taskStatusTable.Start(taskNameMirrorUpdate)
defer taskStatusTable.Stop(taskNameMirrorUpdate)
log.Trace("Doing: MirrorUpdate")
if err := x.Where("next_update_unix<=?", time.Now().Unix()).Iterate(new(Mirror), func(idx int, bean any) error {
m := bean.(*Mirror)
if m.Repo == nil {
log.Error("Disconnected mirror repository found: %d", m.ID)
return nil
}
MirrorQueue.Add(m.RepoID)
return nil
}); err != nil {
log.Error("MirrorUpdate: %v", err)
}
}
// SyncMirrors checks and syncs mirrors.
// TODO: sync more mirrors at same time.
func SyncMirrors() {
ctx := context.Background()
// Start listening on new sync requests.
for repoID := range MirrorQueue.Queue() {
log.Trace("SyncMirrors [repo_id: %s]", repoID)
MirrorQueue.Remove(repoID)
m, err := GetMirrorByRepoID(com.StrTo(repoID).MustInt64())
if err != nil {
log.Error("GetMirrorByRepoID [%v]: %v", repoID, err)
continue
}
results, ok := m.runSync()
if !ok {
continue
}
m.ScheduleNextSync()
if err = UpdateMirror(m); err != nil {
log.Error("UpdateMirror [%d]: %v", m.RepoID, err)
continue
}
// TODO:
// - Create "Mirror Sync" webhook event
// - Create mirror sync (create, push and delete) events and trigger the "mirror sync" webhooks
if len(results) == 0 {
log.Trace("SyncMirrors [repo_id: %d]: no commits fetched", m.RepoID)
}
gitRepo, err := git.Open(m.Repo.RepoPath())
if err != nil {
log.Error("Failed to open repository [repo_id: %d]: %v", m.RepoID, err)
continue
}
for _, result := range results {
// Discard GitHub pull requests, i.e. refs/pull/*
if strings.HasPrefix(result.refName, "refs/pull/") {
continue
}
// Delete reference
if result.newCommitID == gitShortEmptyID {
if err = Handle.Actions().MirrorSyncDelete(ctx, m.Repo.MustOwner(), m.Repo, result.refName); err != nil {
log.Error("Failed to create action for mirror sync delete [repo_id: %d]: %v", m.RepoID, err)
}
continue
}
// New reference
isNewRef := false
if result.oldCommitID == gitShortEmptyID {
if err = Handle.Actions().MirrorSyncCreate(ctx, m.Repo.MustOwner(), m.Repo, result.refName); err != nil {
log.Error("Failed to create action for mirror sync create [repo_id: %d]: %v", m.RepoID, err)
continue
}
isNewRef = true
}
// Push commits
var commits []*git.Commit
var oldCommitID string
var newCommitID string
if !isNewRef {
oldCommitID, err = gitRepo.RevParse(result.oldCommitID)
if err != nil {
log.Error("Failed to parse revision [repo_id: %d, old_commit_id: %s]: %v", m.RepoID, result.oldCommitID, err)
continue
}
newCommitID, err = gitRepo.RevParse(result.newCommitID)
if err != nil {
log.Error("Failed to parse revision [repo_id: %d, new_commit_id: %s]: %v", m.RepoID, result.newCommitID, err)
continue
}
commits, err = gitRepo.RevList([]string{oldCommitID + "..." + newCommitID})
if err != nil {
log.Error("Failed to list commits [repo_id: %d, old_commit_id: %s, new_commit_id: %s]: %v", m.RepoID, oldCommitID, newCommitID, err)
continue
}
} else if gitRepo.HasBranch(result.refName) {
refNewCommit, err := gitRepo.BranchCommit(result.refName)
if err != nil {
log.Error("Failed to get branch commit [repo_id: %d, branch: %s]: %v", m.RepoID, result.refName, err)
continue
}
// TODO(unknwon): Get the commits for the new ref until the closest ancestor branch like GitHub does.
commits, err = refNewCommit.Ancestors(git.LogOptions{MaxCount: 9})
if err != nil {
log.Error("Failed to get ancestors [repo_id: %d, commit_id: %s]: %v", m.RepoID, refNewCommit.ID, err)
continue
}
// Put the latest commit in front of ancestors
commits = append([]*git.Commit{refNewCommit}, commits...)
oldCommitID = git.EmptyID
newCommitID = refNewCommit.ID.String()
}
err = Handle.Actions().MirrorSyncPush(ctx,
MirrorSyncPushOptions{
Owner: m.Repo.MustOwner(),
Repo: m.Repo,
RefName: result.refName,
OldCommitID: oldCommitID,
NewCommitID: newCommitID,
Commits: CommitsToPushCommits(commits),
},
)
if err != nil {
log.Error("Failed to create action for mirror sync push [repo_id: %d]: %v", m.RepoID, err)
continue
}
}
if _, err = x.Exec("UPDATE mirror SET updated_unix = ? WHERE repo_id = ?", time.Now().Unix(), m.RepoID); err != nil {
log.Error("Update 'mirror.updated_unix' [%d]: %v", m.RepoID, err)
continue
}
// Get latest commit date and compare to current repository updated time,
// update if latest commit date is newer.
latestCommitTime, err := gitRepo.LatestCommitTime()
if err != nil {
log.Error("GetLatestCommitDate [%d]: %v", m.RepoID, err)
continue
} else if !latestCommitTime.After(m.Repo.Updated) {
continue
}
if _, err = x.Exec("UPDATE repository SET updated_unix = ? WHERE id = ?", latestCommitTime.Unix(), m.RepoID); err != nil {
log.Error("Update 'repository.updated_unix' [%d]: %v", m.RepoID, err)
continue
}
}
}
func InitSyncMirrors() {
go SyncMirrors()
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/users_test.go | internal/database/users_test.go | // Copyright 2020 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gorm.io/gorm"
"gogs.io/gogs/internal/auth"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/dbutil"
"gogs.io/gogs/internal/errutil"
"gogs.io/gogs/internal/osutil"
"gogs.io/gogs/internal/repoutil"
"gogs.io/gogs/internal/userutil"
"gogs.io/gogs/public"
)
func TestUser_BeforeCreate(t *testing.T) {
now := time.Now()
db := &gorm.DB{
Config: &gorm.Config{
SkipDefaultTransaction: true,
NowFunc: func() time.Time {
return now
},
},
}
t.Run("CreatedUnix has been set", func(t *testing.T) {
user := &User{
CreatedUnix: 1,
}
_ = user.BeforeCreate(db)
assert.Equal(t, int64(1), user.CreatedUnix)
assert.Equal(t, int64(0), user.UpdatedUnix)
})
t.Run("CreatedUnix has not been set", func(t *testing.T) {
user := &User{}
_ = user.BeforeCreate(db)
assert.Equal(t, db.NowFunc().Unix(), user.CreatedUnix)
assert.Equal(t, db.NowFunc().Unix(), user.UpdatedUnix)
})
}
func TestUser_AfterFind(t *testing.T) {
now := time.Now()
db := &gorm.DB{
Config: &gorm.Config{
SkipDefaultTransaction: true,
NowFunc: func() time.Time {
return now
},
},
}
user := &User{
FullName: "user1<script src=http://localhost:8181/xss.js>",
CreatedUnix: now.Unix(),
UpdatedUnix: now.Unix(),
}
_ = user.AfterFind(db)
assert.Equal(t, "user1", user.FullName)
assert.Equal(t, user.CreatedUnix, user.Created.Unix())
assert.Equal(t, user.UpdatedUnix, user.Updated.Unix())
}
func TestUsers(t *testing.T) {
if testing.Short() {
t.Skip()
}
t.Parallel()
ctx := context.Background()
s := &UsersStore{
db: newTestDB(t, "UsersStore"),
}
for _, tc := range []struct {
name string
test func(t *testing.T, ctx context.Context, s *UsersStore)
}{
{"Authenticate", usersAuthenticate},
{"ChangeUsername", usersChangeUsername},
{"Count", usersCount},
{"Create", usersCreate},
{"DeleteCustomAvatar", usersDeleteCustomAvatar},
{"DeleteByID", usersDeleteByID},
{"DeleteInactivated", usersDeleteInactivated},
{"GetByEmail", usersGetByEmail},
{"GetByID", usersGetByID},
{"GetByUsername", usersGetByUsername},
{"GetByKeyID", usersGetByKeyID},
{"GetMailableEmailsByUsernames", usersGetMailableEmailsByUsernames},
{"IsUsernameUsed", usersIsUsernameUsed},
{"List", usersList},
{"ListFollowers", usersListFollowers},
{"ListFollowings", usersListFollowings},
{"SearchByName", usersSearchByName},
{"Update", usersUpdate},
{"UseCustomAvatar", usersUseCustomAvatar},
{"AddEmail", usersAddEmail},
{"GetEmail", usersGetEmail},
{"ListEmails", usersListEmails},
{"MarkEmailActivated", usersMarkEmailActivated},
{"MarkEmailPrimary", usersMarkEmailPrimary},
{"DeleteEmail", usersDeleteEmail},
{"Follow", usersFollow},
{"IsFollowing", usersIsFollowing},
{"Unfollow", usersUnfollow},
} {
t.Run(tc.name, func(t *testing.T) {
t.Cleanup(func() {
err := clearTables(t, s.db)
require.NoError(t, err)
})
tc.test(t, ctx, s)
})
if t.Failed() {
break
}
}
}
func usersAuthenticate(t *testing.T, ctx context.Context, s *UsersStore) {
password := "pa$$word"
alice, err := s.Create(ctx, "alice", "alice@example.com",
CreateUserOptions{
Password: password,
},
)
require.NoError(t, err)
t.Run("user not found", func(t *testing.T) {
_, err := s.Authenticate(ctx, "bob", password, -1)
wantErr := auth.ErrBadCredentials{Args: map[string]any{"login": "bob"}}
assert.Equal(t, wantErr, err)
})
t.Run("invalid password", func(t *testing.T) {
_, err := s.Authenticate(ctx, alice.Name, "bad_password", -1)
wantErr := auth.ErrBadCredentials{Args: map[string]any{"login": alice.Name, "userID": alice.ID}}
assert.Equal(t, wantErr, err)
})
t.Run("via email and password", func(t *testing.T) {
user, err := s.Authenticate(ctx, alice.Email, password, -1)
require.NoError(t, err)
assert.Equal(t, alice.Name, user.Name)
})
t.Run("via username and password", func(t *testing.T) {
user, err := s.Authenticate(ctx, alice.Name, password, -1)
require.NoError(t, err)
assert.Equal(t, alice.Name, user.Name)
})
t.Run("login source mismatch", func(t *testing.T) {
_, err := s.Authenticate(ctx, alice.Email, password, 1)
gotErr := fmt.Sprintf("%v", err)
wantErr := ErrLoginSourceMismatch{args: map[string]any{"actual": 0, "expect": 1}}.Error()
assert.Equal(t, wantErr, gotErr)
})
t.Run("via login source", func(t *testing.T) {
loginSourcesStore := newLoginSourcesStore(s.db, NewMockLoginSourceFilesStore())
loginSource, err := loginSourcesStore.Create(
ctx,
CreateLoginSourceOptions{
Type: auth.Mock,
Name: "mock-1",
Activated: true,
Config: mockProviderConfig{
ExternalAccount: &auth.ExternalAccount{},
},
},
)
require.NoError(t, err)
bob, err := s.Create(ctx, "bob", "bob@example.com",
CreateUserOptions{
Password: password,
LoginSource: 1,
},
)
require.NoError(t, err)
user, err := s.Authenticate(ctx, bob.Email, password, loginSource.ID)
require.NoError(t, err)
assert.Equal(t, bob.Name, user.Name)
})
t.Run("new user via login source", func(t *testing.T) {
loginSourcesStore := newLoginSourcesStore(s.db, NewMockLoginSourceFilesStore())
loginSource, err := loginSourcesStore.Create(
ctx,
CreateLoginSourceOptions{
Type: auth.Mock,
Name: "mock-2",
Activated: true,
Config: mockProviderConfig{
ExternalAccount: &auth.ExternalAccount{
Name: "cindy",
Email: "cindy@example.com",
},
},
},
)
require.NoError(t, err)
user, err := s.Authenticate(ctx, "cindy", password, loginSource.ID)
require.NoError(t, err)
assert.Equal(t, "cindy", user.Name)
user, err = s.GetByUsername(ctx, "cindy")
require.NoError(t, err)
assert.Equal(t, "cindy@example.com", user.Email)
})
}
func usersChangeUsername(t *testing.T, ctx context.Context, s *UsersStore) {
alice, err := s.Create(
ctx,
"alice",
"alice@example.com",
CreateUserOptions{
Activated: true,
},
)
require.NoError(t, err)
t.Run("name not allowed", func(t *testing.T) {
err := s.ChangeUsername(ctx, alice.ID, "-")
wantErr := ErrNameNotAllowed{
args: errutil.Args{
"reason": "reserved",
"name": "-",
},
}
assert.Equal(t, wantErr, err)
})
t.Run("name already exists", func(t *testing.T) {
bob, err := s.Create(
ctx,
"bob",
"bob@example.com",
CreateUserOptions{
Activated: true,
},
)
require.NoError(t, err)
err = s.ChangeUsername(ctx, alice.ID, bob.Name)
wantErr := ErrUserAlreadyExist{
args: errutil.Args{
"name": bob.Name,
},
}
assert.Equal(t, wantErr, err)
})
tempRepositoryRoot := filepath.Join(os.TempDir(), "usersChangeUsername-tempRepositoryRoot")
conf.SetMockRepository(
t,
conf.RepositoryOpts{
Root: tempRepositoryRoot,
},
)
err = os.RemoveAll(tempRepositoryRoot)
require.NoError(t, err)
defer func() { _ = os.RemoveAll(tempRepositoryRoot) }()
tempServerAppDataPath := filepath.Join(os.TempDir(), "usersChangeUsername-tempServerAppDataPath")
conf.SetMockServer(
t,
conf.ServerOpts{
AppDataPath: tempServerAppDataPath,
},
)
err = os.RemoveAll(tempServerAppDataPath)
require.NoError(t, err)
defer func() { _ = os.RemoveAll(tempServerAppDataPath) }()
repo, err := newReposStore(s.db).Create(
ctx,
alice.ID,
CreateRepoOptions{
Name: "test-repo-1",
},
)
require.NoError(t, err)
// TODO: Use PullRequests.Create to replace SQL hack when the method is available.
err = s.db.Exec(`INSERT INTO pull_request (head_user_name) VALUES (?)`, alice.Name).Error
require.NoError(t, err)
err = s.db.Model(&User{}).Where("id = ?", alice.ID).Update("updated_unix", 0).Error
require.NoError(t, err)
err = os.MkdirAll(repoutil.UserPath(alice.Name), os.ModePerm)
require.NoError(t, err)
err = os.MkdirAll(repoutil.RepositoryLocalPath(repo.ID), os.ModePerm)
require.NoError(t, err)
err = os.MkdirAll(repoutil.RepositoryLocalWikiPath(repo.ID), os.ModePerm)
require.NoError(t, err)
// Make sure mock data is set up correctly
// TODO: Use PullRequests.GetByID to replace SQL hack when the method is available.
var headUserName string
err = s.db.Model(&PullRequest{}).Select("head_user_name").Row().Scan(&headUserName)
require.NoError(t, err)
assert.Equal(t, headUserName, alice.Name)
var updatedUnix int64
err = s.db.Model(&User{}).Select("updated_unix").Where("id = ?", alice.ID).Row().Scan(&updatedUnix)
require.NoError(t, err)
assert.Equal(t, int64(0), updatedUnix)
assert.True(t, osutil.IsExist(repoutil.UserPath(alice.Name)))
assert.True(t, osutil.IsExist(repoutil.RepositoryLocalPath(repo.ID)))
assert.True(t, osutil.IsExist(repoutil.RepositoryLocalWikiPath(repo.ID)))
const newUsername = "alice-new"
err = s.ChangeUsername(ctx, alice.ID, newUsername)
require.NoError(t, err)
// TODO: Use PullRequests.GetByID to replace SQL hack when the method is available.
err = s.db.Model(&PullRequest{}).Select("head_user_name").Row().Scan(&headUserName)
require.NoError(t, err)
assert.Equal(t, headUserName, newUsername)
assert.True(t, osutil.IsExist(repoutil.UserPath(newUsername)))
assert.False(t, osutil.IsExist(repoutil.UserPath(alice.Name)))
assert.False(t, osutil.IsExist(repoutil.RepositoryLocalPath(repo.ID)))
assert.False(t, osutil.IsExist(repoutil.RepositoryLocalWikiPath(repo.ID)))
alice, err = s.GetByID(ctx, alice.ID)
require.NoError(t, err)
assert.Equal(t, newUsername, alice.Name)
assert.Equal(t, s.db.NowFunc().Unix(), alice.UpdatedUnix)
// Change the cases of the username should just be fine
err = s.ChangeUsername(ctx, alice.ID, strings.ToUpper(newUsername))
require.NoError(t, err)
alice, err = s.GetByID(ctx, alice.ID)
require.NoError(t, err)
assert.Equal(t, strings.ToUpper(newUsername), alice.Name)
}
func usersCount(t *testing.T, ctx context.Context, s *UsersStore) {
// Has no user initially
got := s.Count(ctx)
assert.Equal(t, int64(0), got)
_, err := s.Create(ctx, "alice", "alice@example.com", CreateUserOptions{})
require.NoError(t, err)
got = s.Count(ctx)
assert.Equal(t, int64(1), got)
// Create an organization shouldn't count
// TODO: Use Orgs.Create to replace SQL hack when the method is available.
org1, err := s.Create(ctx, "org1", "org1@example.com", CreateUserOptions{})
require.NoError(t, err)
err = s.db.Exec(
dbutil.Quote("UPDATE %s SET type = ? WHERE id = ?", "user"),
UserTypeOrganization, org1.ID,
).Error
require.NoError(t, err)
got = s.Count(ctx)
assert.Equal(t, int64(1), got)
}
func usersCreate(t *testing.T, ctx context.Context, s *UsersStore) {
alice, err := s.Create(
ctx,
"alice",
"alice@example.com",
CreateUserOptions{
Activated: true,
},
)
require.NoError(t, err)
t.Run("name not allowed", func(t *testing.T) {
_, err := s.Create(ctx, "-", "", CreateUserOptions{})
wantErr := ErrNameNotAllowed{
args: errutil.Args{
"reason": "reserved",
"name": "-",
},
}
assert.Equal(t, wantErr, err)
})
t.Run("name already exists", func(t *testing.T) {
_, err := s.Create(ctx, alice.Name, "", CreateUserOptions{})
wantErr := ErrUserAlreadyExist{
args: errutil.Args{
"name": alice.Name,
},
}
assert.Equal(t, wantErr, err)
})
t.Run("email already exists", func(t *testing.T) {
_, err := s.Create(ctx, "bob", alice.Email, CreateUserOptions{})
wantErr := ErrEmailAlreadyUsed{
args: errutil.Args{
"email": alice.Email,
},
}
assert.Equal(t, wantErr, err)
})
user, err := s.GetByUsername(ctx, alice.Name)
require.NoError(t, err)
assert.Equal(t, s.db.NowFunc().Format(time.RFC3339), user.Created.UTC().Format(time.RFC3339))
assert.Equal(t, s.db.NowFunc().Format(time.RFC3339), user.Updated.UTC().Format(time.RFC3339))
}
func usersDeleteCustomAvatar(t *testing.T, ctx context.Context, s *UsersStore) {
alice, err := s.Create(ctx, "alice", "alice@example.com", CreateUserOptions{})
require.NoError(t, err)
avatar, err := public.Files.ReadFile("img/avatar_default.png")
require.NoError(t, err)
avatarPath := userutil.CustomAvatarPath(alice.ID)
_ = os.Remove(avatarPath)
defer func() { _ = os.Remove(avatarPath) }()
err = s.UseCustomAvatar(ctx, alice.ID, avatar)
require.NoError(t, err)
// Make sure avatar is saved and the user flag is updated.
got := osutil.IsFile(avatarPath)
assert.True(t, got)
alice, err = s.GetByID(ctx, alice.ID)
require.NoError(t, err)
assert.True(t, alice.UseCustomAvatar)
// Delete avatar should remove the file and revert the user flag.
err = s.DeleteCustomAvatar(ctx, alice.ID)
require.NoError(t, err)
got = osutil.IsFile(avatarPath)
assert.False(t, got)
alice, err = s.GetByID(ctx, alice.ID)
require.NoError(t, err)
assert.False(t, alice.UseCustomAvatar)
}
func usersDeleteByID(t *testing.T, ctx context.Context, s *UsersStore) {
reposStore := newReposStore(s.db)
t.Run("user still has repository ownership", func(t *testing.T) {
alice, err := s.Create(ctx, "alice", "alice@exmaple.com", CreateUserOptions{})
require.NoError(t, err)
_, err = reposStore.Create(ctx, alice.ID, CreateRepoOptions{Name: "repo1"})
require.NoError(t, err)
err = s.DeleteByID(ctx, alice.ID, false)
wantErr := ErrUserOwnRepos{errutil.Args{"userID": alice.ID}}
assert.Equal(t, wantErr, err)
})
t.Run("user still has organization membership", func(t *testing.T) {
bob, err := s.Create(ctx, "bob", "bob@exmaple.com", CreateUserOptions{})
require.NoError(t, err)
// TODO: Use Orgs.Create to replace SQL hack when the method is available.
org1, err := s.Create(ctx, "org1", "org1@example.com", CreateUserOptions{})
require.NoError(t, err)
err = s.db.Exec(
dbutil.Quote("UPDATE %s SET type = ? WHERE id IN (?)", "user"),
UserTypeOrganization, org1.ID,
).Error
require.NoError(t, err)
// TODO: Use Orgs.Join to replace SQL hack when the method is available.
err = s.db.Exec(`INSERT INTO org_user (uid, org_id) VALUES (?, ?)`, bob.ID, org1.ID).Error
require.NoError(t, err)
err = s.DeleteByID(ctx, bob.ID, false)
wantErr := ErrUserHasOrgs{errutil.Args{"userID": bob.ID}}
assert.Equal(t, wantErr, err)
})
cindy, err := s.Create(ctx, "cindy", "cindy@exmaple.com", CreateUserOptions{})
require.NoError(t, err)
frank, err := s.Create(ctx, "frank", "frank@exmaple.com", CreateUserOptions{})
require.NoError(t, err)
repo2, err := reposStore.Create(ctx, cindy.ID, CreateRepoOptions{Name: "repo2"})
require.NoError(t, err)
testUser, err := s.Create(ctx, "testUser", "testUser@exmaple.com", CreateUserOptions{})
require.NoError(t, err)
// Mock watches, stars and follows
err = reposStore.Watch(ctx, testUser.ID, repo2.ID)
require.NoError(t, err)
err = reposStore.Star(ctx, testUser.ID, repo2.ID)
require.NoError(t, err)
err = s.Follow(ctx, testUser.ID, cindy.ID)
require.NoError(t, err)
err = s.Follow(ctx, frank.ID, testUser.ID)
require.NoError(t, err)
// Mock "authorized_keys" file
// TODO: Use PublicKeys.Add to replace SQL hack when the method is available.
publicKey := &PublicKey{
OwnerID: testUser.ID,
Name: "test-key",
Fingerprint: "12:f8:7e:78:61:b4:bf:e2:de:24:15:96:4e:d4:72:53",
Content: "test-key-content",
}
err = s.db.Create(publicKey).Error
require.NoError(t, err)
tempSSHRootPath := filepath.Join(os.TempDir(), "usersDeleteByID-tempSSHRootPath")
conf.SetMockSSH(t, conf.SSHOpts{RootPath: tempSSHRootPath})
err = newPublicKeysStore(s.db).RewriteAuthorizedKeys()
require.NoError(t, err)
// Mock issue assignee
// TODO: Use Issues.Assign to replace SQL hack when the method is available.
issue := &Issue{
RepoID: repo2.ID,
Index: 1,
PosterID: cindy.ID,
Title: "test-issue",
AssigneeID: testUser.ID,
}
err = s.db.Create(issue).Error
require.NoError(t, err)
// Mock random entries in related tables
for _, table := range []any{
&AccessToken{UserID: testUser.ID},
&Collaboration{UserID: testUser.ID},
&Access{UserID: testUser.ID},
&Action{UserID: testUser.ID},
&IssueUser{UserID: testUser.ID},
&EmailAddress{UserID: testUser.ID},
} {
err = s.db.Create(table).Error
require.NoError(t, err, "table for %T", table)
}
// Mock user directory
tempRepositoryRoot := filepath.Join(os.TempDir(), "usersDeleteByID-tempRepositoryRoot")
conf.SetMockRepository(t, conf.RepositoryOpts{Root: tempRepositoryRoot})
tempUserPath := repoutil.UserPath(testUser.Name)
err = os.MkdirAll(tempUserPath, os.ModePerm)
require.NoError(t, err)
// Mock user custom avatar
tempPictureAvatarUploadPath := filepath.Join(os.TempDir(), "usersDeleteByID-tempPictureAvatarUploadPath")
conf.SetMockPicture(t, conf.PictureOpts{AvatarUploadPath: tempPictureAvatarUploadPath})
err = os.MkdirAll(tempPictureAvatarUploadPath, os.ModePerm)
require.NoError(t, err)
tempCustomAvatarPath := userutil.CustomAvatarPath(testUser.ID)
err = os.WriteFile(tempCustomAvatarPath, []byte("test"), 0600)
require.NoError(t, err)
// Verify mock data
repo2, err = reposStore.GetByID(ctx, repo2.ID)
require.NoError(t, err)
assert.Equal(t, 2, repo2.NumWatches) // The owner is watching the repo by default.
assert.Equal(t, 1, repo2.NumStars)
cindy, err = s.GetByID(ctx, cindy.ID)
require.NoError(t, err)
assert.Equal(t, 1, cindy.NumFollowers)
frank, err = s.GetByID(ctx, frank.ID)
require.NoError(t, err)
assert.Equal(t, 1, frank.NumFollowing)
authorizedKeys, err := os.ReadFile(authorizedKeysPath())
require.NoError(t, err)
assert.Contains(t, string(authorizedKeys), fmt.Sprintf("key-%d", publicKey.ID))
assert.Contains(t, string(authorizedKeys), publicKey.Content)
// TODO: Use Issues.GetByID to replace SQL hack when the method is available.
err = s.db.First(issue, issue.ID).Error
require.NoError(t, err)
assert.Equal(t, testUser.ID, issue.AssigneeID)
relatedTables := []any{
&Watch{UserID: testUser.ID},
&Star{UserID: testUser.ID},
&Follow{UserID: testUser.ID},
&PublicKey{OwnerID: testUser.ID},
&AccessToken{UserID: testUser.ID},
&Collaboration{UserID: testUser.ID},
&Access{UserID: testUser.ID},
&Action{UserID: testUser.ID},
&IssueUser{UserID: testUser.ID},
&EmailAddress{UserID: testUser.ID},
}
for _, table := range relatedTables {
var count int64
err = s.db.Model(table).Where(table).Count(&count).Error
require.NoError(t, err, "table for %T", table)
assert.NotZero(t, count, "table for %T", table)
}
assert.True(t, osutil.IsExist(tempUserPath))
assert.True(t, osutil.IsExist(tempCustomAvatarPath))
// Pull the trigger
err = s.DeleteByID(ctx, testUser.ID, false)
require.NoError(t, err)
// Verify after-the-fact data
repo2, err = reposStore.GetByID(ctx, repo2.ID)
require.NoError(t, err)
assert.Equal(t, 1, repo2.NumWatches) // The owner is watching the repo by default.
assert.Equal(t, 0, repo2.NumStars)
cindy, err = s.GetByID(ctx, cindy.ID)
require.NoError(t, err)
assert.Equal(t, 0, cindy.NumFollowers)
frank, err = s.GetByID(ctx, frank.ID)
require.NoError(t, err)
assert.Equal(t, 0, frank.NumFollowing)
authorizedKeys, err = os.ReadFile(authorizedKeysPath())
require.NoError(t, err)
assert.Empty(t, authorizedKeys)
// TODO: Use Issues.GetByID to replace SQL hack when the method is available.
err = s.db.First(issue, issue.ID).Error
require.NoError(t, err)
assert.Equal(t, int64(0), issue.AssigneeID)
for _, table := range []any{
&Watch{UserID: testUser.ID},
&Star{UserID: testUser.ID},
&Follow{UserID: testUser.ID},
&PublicKey{OwnerID: testUser.ID},
&AccessToken{UserID: testUser.ID},
&Collaboration{UserID: testUser.ID},
&Access{UserID: testUser.ID},
&Action{UserID: testUser.ID},
&IssueUser{UserID: testUser.ID},
&EmailAddress{UserID: testUser.ID},
} {
var count int64
err = s.db.Model(table).Where(table).Count(&count).Error
require.NoError(t, err, "table for %T", table)
assert.Equal(t, int64(0), count, "table for %T", table)
}
assert.False(t, osutil.IsExist(tempUserPath))
assert.False(t, osutil.IsExist(tempCustomAvatarPath))
_, err = s.GetByID(ctx, testUser.ID)
wantErr := ErrUserNotExist{errutil.Args{"userID": testUser.ID}}
assert.Equal(t, wantErr, err)
}
func usersDeleteInactivated(t *testing.T, ctx context.Context, s *UsersStore) {
// User with repository ownership should be skipped
alice, err := s.Create(ctx, "alice", "alice@exmaple.com", CreateUserOptions{})
require.NoError(t, err)
reposStore := newReposStore(s.db)
_, err = reposStore.Create(ctx, alice.ID, CreateRepoOptions{Name: "repo1"})
require.NoError(t, err)
// User with organization membership should be skipped
bob, err := s.Create(ctx, "bob", "bob@exmaple.com", CreateUserOptions{})
require.NoError(t, err)
// TODO: Use Orgs.Create to replace SQL hack when the method is available.
org1, err := s.Create(ctx, "org1", "org1@example.com", CreateUserOptions{})
require.NoError(t, err)
err = s.db.Exec(
dbutil.Quote("UPDATE %s SET type = ? WHERE id IN (?)", "user"),
UserTypeOrganization, org1.ID,
).Error
require.NoError(t, err)
// TODO: Use Orgs.Join to replace SQL hack when the method is available.
err = s.db.Exec(`INSERT INTO org_user (uid, org_id) VALUES (?, ?)`, bob.ID, org1.ID).Error
require.NoError(t, err)
// User activated state should be skipped
_, err = s.Create(ctx, "cindy", "cindy@exmaple.com", CreateUserOptions{Activated: true})
require.NoError(t, err)
// User meant to be deleted
david, err := s.Create(ctx, "david", "david@exmaple.com", CreateUserOptions{})
require.NoError(t, err)
tempSSHRootPath := filepath.Join(os.TempDir(), "usersDeleteInactivated-tempSSHRootPath")
conf.SetMockSSH(t, conf.SSHOpts{RootPath: tempSSHRootPath})
err = s.DeleteInactivated()
require.NoError(t, err)
_, err = s.GetByID(ctx, david.ID)
wantErr := ErrUserNotExist{errutil.Args{"userID": david.ID}}
assert.Equal(t, wantErr, err)
users, err := s.List(ctx, 1, 10)
require.NoError(t, err)
require.Len(t, users, 3)
}
func usersGetByEmail(t *testing.T, ctx context.Context, s *UsersStore) {
t.Run("empty email", func(t *testing.T) {
_, err := s.GetByEmail(ctx, "")
wantErr := ErrUserNotExist{args: errutil.Args{"email": ""}}
assert.Equal(t, wantErr, err)
})
t.Run("ignore organization", func(t *testing.T) {
// TODO: Use Orgs.Create to replace SQL hack when the method is available.
org, err := s.Create(ctx, "gogs", "gogs@exmaple.com", CreateUserOptions{})
require.NoError(t, err)
err = s.db.Model(&User{}).Where("id", org.ID).UpdateColumn("type", UserTypeOrganization).Error
require.NoError(t, err)
_, err = s.GetByEmail(ctx, org.Email)
wantErr := ErrUserNotExist{args: errutil.Args{"email": org.Email}}
assert.Equal(t, wantErr, err)
})
t.Run("by primary email", func(t *testing.T) {
alice, err := s.Create(ctx, "alice", "alice@exmaple.com", CreateUserOptions{})
require.NoError(t, err)
_, err = s.GetByEmail(ctx, alice.Email)
wantErr := ErrUserNotExist{args: errutil.Args{"email": alice.Email}}
assert.Equal(t, wantErr, err)
// Mark user as activated
// TODO: Use UserEmails.Verify to replace SQL hack when the method is available.
err = s.db.Model(&User{}).Where("id", alice.ID).UpdateColumn("is_active", true).Error
require.NoError(t, err)
user, err := s.GetByEmail(ctx, alice.Email)
require.NoError(t, err)
assert.Equal(t, alice.Name, user.Name)
})
t.Run("by secondary email", func(t *testing.T) {
bob, err := s.Create(ctx, "bob", "bob@example.com", CreateUserOptions{})
require.NoError(t, err)
// TODO: Use UserEmails.Create to replace SQL hack when the method is available.
email2 := "bob2@exmaple.com"
err = s.db.Exec(`INSERT INTO email_address (uid, email) VALUES (?, ?)`, bob.ID, email2).Error
require.NoError(t, err)
_, err = s.GetByEmail(ctx, email2)
wantErr := ErrUserNotExist{args: errutil.Args{"email": email2}}
assert.Equal(t, wantErr, err)
// TODO: Use UserEmails.Verify to replace SQL hack when the method is available.
err = s.db.Exec(`UPDATE email_address SET is_activated = ? WHERE email = ?`, true, email2).Error
require.NoError(t, err)
user, err := s.GetByEmail(ctx, email2)
require.NoError(t, err)
assert.Equal(t, bob.Name, user.Name)
})
}
func usersGetByID(t *testing.T, ctx context.Context, s *UsersStore) {
alice, err := s.Create(ctx, "alice", "alice@exmaple.com", CreateUserOptions{})
require.NoError(t, err)
user, err := s.GetByID(ctx, alice.ID)
require.NoError(t, err)
assert.Equal(t, alice.Name, user.Name)
_, err = s.GetByID(ctx, 404)
wantErr := ErrUserNotExist{args: errutil.Args{"userID": int64(404)}}
assert.Equal(t, wantErr, err)
}
func usersGetByUsername(t *testing.T, ctx context.Context, s *UsersStore) {
alice, err := s.Create(ctx, "alice", "alice@exmaple.com", CreateUserOptions{})
require.NoError(t, err)
user, err := s.GetByUsername(ctx, alice.Name)
require.NoError(t, err)
assert.Equal(t, alice.Name, user.Name)
_, err = s.GetByUsername(ctx, "bad_username")
wantErr := ErrUserNotExist{args: errutil.Args{"name": "bad_username"}}
assert.Equal(t, wantErr, err)
}
func usersGetByKeyID(t *testing.T, ctx context.Context, s *UsersStore) {
alice, err := s.Create(ctx, "alice", "alice@exmaple.com", CreateUserOptions{})
require.NoError(t, err)
// TODO: Use PublicKeys.Create to replace SQL hack when the method is available.
publicKey := &PublicKey{
OwnerID: alice.ID,
Name: "test-key",
Fingerprint: "12:f8:7e:78:61:b4:bf:e2:de:24:15:96:4e:d4:72:53",
Content: "test-key-content",
CreatedUnix: s.db.NowFunc().Unix(),
UpdatedUnix: s.db.NowFunc().Unix(),
}
err = s.db.WithContext(ctx).Create(publicKey).Error
require.NoError(t, err)
user, err := s.GetByKeyID(ctx, publicKey.ID)
require.NoError(t, err)
assert.Equal(t, alice.Name, user.Name)
_, err = s.GetByKeyID(ctx, publicKey.ID+1)
wantErr := ErrUserNotExist{args: errutil.Args{"keyID": publicKey.ID + 1}}
assert.Equal(t, wantErr, err)
}
func usersGetMailableEmailsByUsernames(t *testing.T, ctx context.Context, s *UsersStore) {
alice, err := s.Create(ctx, "alice", "alice@exmaple.com", CreateUserOptions{})
require.NoError(t, err)
bob, err := s.Create(ctx, "bob", "bob@exmaple.com", CreateUserOptions{Activated: true})
require.NoError(t, err)
_, err = s.Create(ctx, "cindy", "cindy@exmaple.com", CreateUserOptions{Activated: true})
require.NoError(t, err)
got, err := s.GetMailableEmailsByUsernames(ctx, []string{alice.Name, bob.Name, "ignore-non-exist"})
require.NoError(t, err)
want := []string{bob.Email}
assert.Equal(t, want, got)
}
func usersIsUsernameUsed(t *testing.T, ctx context.Context, s *UsersStore) {
alice, err := s.Create(ctx, "alice", "alice@example.com", CreateUserOptions{})
require.NoError(t, err)
tests := []struct {
name string
username string
excludeUserID int64
want bool
}{
{
name: "no change",
username: alice.Name,
excludeUserID: alice.ID,
want: false,
},
{
name: "change case",
username: strings.ToUpper(alice.Name),
excludeUserID: alice.ID,
want: false,
},
{
name: "not used",
username: "bob",
excludeUserID: alice.ID,
want: false,
},
{
name: "not used when not excluded",
username: "bob",
excludeUserID: 0,
want: false,
},
{
name: "used when not excluded",
username: alice.Name,
excludeUserID: 0,
want: true,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
got := s.IsUsernameUsed(ctx, test.username, test.excludeUserID)
assert.Equal(t, test.want, got)
})
}
}
func usersList(t *testing.T, ctx context.Context, s *UsersStore) {
alice, err := s.Create(ctx, "alice", "alice@example.com", CreateUserOptions{})
require.NoError(t, err)
bob, err := s.Create(ctx, "bob", "bob@example.com", CreateUserOptions{})
require.NoError(t, err)
// Create an organization shouldn't count
// TODO: Use Orgs.Create to replace SQL hack when the method is available.
org1, err := s.Create(ctx, "org1", "org1@example.com", CreateUserOptions{})
require.NoError(t, err)
err = s.db.Exec(
dbutil.Quote("UPDATE %s SET type = ? WHERE id = ?", "user"),
UserTypeOrganization, org1.ID,
).Error
require.NoError(t, err)
got, err := s.List(ctx, 1, 1)
require.NoError(t, err)
require.Len(t, got, 1)
assert.Equal(t, alice.ID, got[0].ID)
got, err = s.List(ctx, 2, 1)
require.NoError(t, err)
require.Len(t, got, 1)
assert.Equal(t, bob.ID, got[0].ID)
got, err = s.List(ctx, 1, 3)
require.NoError(t, err)
require.Len(t, got, 2)
assert.Equal(t, alice.ID, got[0].ID)
assert.Equal(t, bob.ID, got[1].ID)
}
func usersListFollowers(t *testing.T, ctx context.Context, s *UsersStore) {
john, err := s.Create(ctx, "john", "john@example.com", CreateUserOptions{})
require.NoError(t, err)
got, err := s.ListFollowers(ctx, john.ID, 1, 1)
require.NoError(t, err)
assert.Empty(t, got)
alice, err := s.Create(ctx, "alice", "alice@example.com", CreateUserOptions{})
require.NoError(t, err)
bob, err := s.Create(ctx, "bob", "bob@example.com", CreateUserOptions{})
require.NoError(t, err)
err = s.Follow(ctx, alice.ID, john.ID)
require.NoError(t, err)
err = s.Follow(ctx, bob.ID, john.ID)
require.NoError(t, err)
// First page only has bob
got, err = s.ListFollowers(ctx, john.ID, 1, 1)
require.NoError(t, err)
require.Len(t, got, 1)
assert.Equal(t, bob.ID, got[0].ID)
// Second page only has alice
got, err = s.ListFollowers(ctx, john.ID, 2, 1)
require.NoError(t, err)
require.Len(t, got, 1)
assert.Equal(t, alice.ID, got[0].ID)
}
func usersListFollowings(t *testing.T, ctx context.Context, s *UsersStore) {
john, err := s.Create(ctx, "john", "john@example.com", CreateUserOptions{})
require.NoError(t, err)
got, err := s.ListFollowers(ctx, john.ID, 1, 1)
require.NoError(t, err)
assert.Empty(t, got)
alice, err := s.Create(ctx, "alice", "alice@example.com", CreateUserOptions{})
require.NoError(t, err)
bob, err := s.Create(ctx, "bob", "bob@example.com", CreateUserOptions{})
require.NoError(t, err)
err = s.Follow(ctx, john.ID, alice.ID)
require.NoError(t, err)
err = s.Follow(ctx, john.ID, bob.ID)
require.NoError(t, err)
// First page only has bob
got, err = s.ListFollowings(ctx, john.ID, 1, 1)
require.NoError(t, err)
require.Len(t, got, 1)
assert.Equal(t, bob.ID, got[0].ID)
// Second page only has alice
got, err = s.ListFollowings(ctx, john.ID, 2, 1)
require.NoError(t, err)
require.Len(t, got, 1)
assert.Equal(t, alice.ID, got[0].ID)
}
func usersSearchByName(t *testing.T, ctx context.Context, s *UsersStore) {
alice, err := s.Create(ctx, "alice", "alice@example.com", CreateUserOptions{FullName: "Alice Jordan"})
require.NoError(t, err)
bob, err := s.Create(ctx, "bob", "bob@example.com", CreateUserOptions{FullName: "Bob Jordan"})
require.NoError(t, err)
t.Run("search for username alice", func(t *testing.T) {
users, count, err := s.SearchByName(ctx, "Li", 1, 1, "")
require.NoError(t, err)
require.Len(t, users, int(count))
assert.Equal(t, int64(1), count)
assert.Equal(t, alice.ID, users[0].ID)
})
t.Run("search for username bob", func(t *testing.T) {
users, count, err := s.SearchByName(ctx, "oB", 1, 1, "")
require.NoError(t, err)
require.Len(t, users, int(count))
assert.Equal(t, int64(1), count)
assert.Equal(t, bob.ID, users[0].ID)
})
t.Run("search for full name jordan", func(t *testing.T) {
users, count, err := s.SearchByName(ctx, "Jo", 1, 10, "")
require.NoError(t, err)
require.Len(t, users, int(count))
assert.Equal(t, int64(2), count)
})
t.Run("search for full name jordan ORDER BY id DESC LIMIT 1", func(t *testing.T) {
users, count, err := s.SearchByName(ctx, "Jo", 1, 1, "id DESC")
require.NoError(t, err)
require.Len(t, users, 1)
assert.Equal(t, int64(2), count)
assert.Equal(t, bob.ID, users[0].ID)
})
}
func usersUpdate(t *testing.T, ctx context.Context, s *UsersStore) {
const oldPassword = "Password"
alice, err := s.Create(
ctx,
"alice",
"alice@example.com",
CreateUserOptions{
FullName: "FullName",
Password: oldPassword,
LoginSource: 9,
LoginName: "LoginName",
Location: "Location",
Website: "Website",
Activated: false,
Admin: false,
},
)
require.NoError(t, err)
t.Run("update password", func(t *testing.T) {
got := userutil.ValidatePassword(alice.Password, alice.Salt, oldPassword)
require.True(t, got)
newPassword := "NewPassword"
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | true |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/error.go | internal/database/error.go | // Copyright 2015 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"fmt"
)
// __ __.__ __ .__
// / \ / \__| | _|__|
// \ \/\/ / | |/ / |
// \ /| | <| |
// \__/\ / |__|__|_ \__|
// \/ \/
type ErrWikiAlreadyExist struct {
Title string
}
func IsErrWikiAlreadyExist(err error) bool {
_, ok := err.(ErrWikiAlreadyExist)
return ok
}
func (err ErrWikiAlreadyExist) Error() string {
return fmt.Sprintf("wiki page already exists [title: %s]", err.Title)
}
// __________ ___. .__ .__ ____ __.
// \______ \__ _\_ |__ | | |__| ____ | |/ _|____ ___.__.
// | ___/ | \ __ \| | | |/ ___\ | <_/ __ < | |
// | | | | / \_\ \ |_| \ \___ | | \ ___/\___ |
// |____| |____/|___ /____/__|\___ > |____|__ \___ > ____|
// \/ \/ \/ \/\/
type ErrKeyUnableVerify struct {
Result string
}
func IsErrKeyUnableVerify(err error) bool {
_, ok := err.(ErrKeyUnableVerify)
return ok
}
func (err ErrKeyUnableVerify) Error() string {
return fmt.Sprintf("Unable to verify key content [result: %s]", err.Result)
}
type ErrKeyNotExist struct {
ID int64
}
func IsErrKeyNotExist(err error) bool {
_, ok := err.(ErrKeyNotExist)
return ok
}
func (err ErrKeyNotExist) Error() string {
return fmt.Sprintf("public key does not exist [id: %d]", err.ID)
}
type ErrKeyAlreadyExist struct {
OwnerID int64
Content string
}
func IsErrKeyAlreadyExist(err error) bool {
_, ok := err.(ErrKeyAlreadyExist)
return ok
}
func (err ErrKeyAlreadyExist) Error() string {
return fmt.Sprintf("public key already exists [owner_id: %d, content: %s]", err.OwnerID, err.Content)
}
type ErrKeyNameAlreadyUsed struct {
OwnerID int64
Name string
}
func IsErrKeyNameAlreadyUsed(err error) bool {
_, ok := err.(ErrKeyNameAlreadyUsed)
return ok
}
func (err ErrKeyNameAlreadyUsed) Error() string {
return fmt.Sprintf("public key already exists [owner_id: %d, name: %s]", err.OwnerID, err.Name)
}
type ErrKeyAccessDenied struct {
UserID int64
KeyID int64
Note string
}
func IsErrKeyAccessDenied(err error) bool {
_, ok := err.(ErrKeyAccessDenied)
return ok
}
func (err ErrKeyAccessDenied) Error() string {
return fmt.Sprintf("user does not have access to the key [user_id: %d, key_id: %d, note: %s]",
err.UserID, err.KeyID, err.Note)
}
type ErrDeployKeyAlreadyExist struct {
KeyID int64
RepoID int64
}
func IsErrDeployKeyAlreadyExist(err error) bool {
_, ok := err.(ErrDeployKeyAlreadyExist)
return ok
}
func (err ErrDeployKeyAlreadyExist) Error() string {
return fmt.Sprintf("public key already exists [key_id: %d, repo_id: %d]", err.KeyID, err.RepoID)
}
type ErrDeployKeyNameAlreadyUsed struct {
RepoID int64
Name string
}
func IsErrDeployKeyNameAlreadyUsed(err error) bool {
_, ok := err.(ErrDeployKeyNameAlreadyUsed)
return ok
}
func (err ErrDeployKeyNameAlreadyUsed) Error() string {
return fmt.Sprintf("public key already exists [repo_id: %d, name: %s]", err.RepoID, err.Name)
}
// ________ .__ __ .__
// \_____ \_______ _________ ____ |__|____________ _/ |_|__| ____ ____
// / | \_ __ \/ ___\__ \ / \| \___ /\__ \\ __\ |/ _ \ / \
// / | \ | \/ /_/ > __ \| | \ |/ / / __ \| | | ( <_> ) | \
// \_______ /__| \___ (____ /___| /__/_____ \(____ /__| |__|\____/|___| /
// \/ /_____/ \/ \/ \/ \/ \/
type ErrLastOrgOwner struct {
UID int64
}
func IsErrLastOrgOwner(err error) bool {
_, ok := err.(ErrLastOrgOwner)
return ok
}
func (err ErrLastOrgOwner) Error() string {
return fmt.Sprintf("user is the last member of owner team [uid: %d]", err.UID)
}
// __________ .__ __
// \______ \ ____ ______ ____ _____|__|/ |_ ___________ ___.__.
// | _// __ \\____ \ / _ \/ ___/ \ __\/ _ \_ __ < | |
// | | \ ___/| |_> > <_> )___ \| || | ( <_> ) | \/\___ |
// |____|_ /\___ > __/ \____/____ >__||__| \____/|__| / ____|
// \/ \/|__| \/ \/
type ErrInvalidCloneAddr struct {
IsURLError bool
IsInvalidPath bool
IsPermissionDenied bool
IsBlockedLocalAddress bool
}
func IsErrInvalidCloneAddr(err error) bool {
_, ok := err.(ErrInvalidCloneAddr)
return ok
}
func (err ErrInvalidCloneAddr) Error() string {
return fmt.Sprintf("invalid clone address [is_url_error: %v, is_invalid_path: %v, is_permission_denied: %v, is_blocked_local_address: %v]",
err.IsURLError, err.IsInvalidPath, err.IsPermissionDenied, err.IsBlockedLocalAddress)
}
type ErrUpdateTaskNotExist struct {
UUID string
}
func IsErrUpdateTaskNotExist(err error) bool {
_, ok := err.(ErrUpdateTaskNotExist)
return ok
}
func (err ErrUpdateTaskNotExist) Error() string {
return fmt.Sprintf("update task does not exist [uuid: %s]", err.UUID)
}
type ErrReleaseAlreadyExist struct {
TagName string
}
func IsErrReleaseAlreadyExist(err error) bool {
_, ok := err.(ErrReleaseAlreadyExist)
return ok
}
func (err ErrReleaseAlreadyExist) Error() string {
return fmt.Sprintf("release tag already exist [tag_name: %s]", err.TagName)
}
type ErrInvalidTagName struct {
TagName string
}
func IsErrInvalidTagName(err error) bool {
_, ok := err.(ErrInvalidTagName)
return ok
}
func (err ErrInvalidTagName) Error() string {
return fmt.Sprintf("release tag name is not valid [tag_name: %s]", err.TagName)
}
type ErrRepoFileAlreadyExist struct {
FileName string
}
func IsErrRepoFileAlreadyExist(err error) bool {
_, ok := err.(ErrRepoFileAlreadyExist)
return ok
}
func (err ErrRepoFileAlreadyExist) Error() string {
return fmt.Sprintf("repository file already exists [file_name: %s]", err.FileName)
}
// ___________
// \__ ___/___ _____ _____
// | |_/ __ \\__ \ / \
// | |\ ___/ / __ \| Y Y \
// |____| \___ >____ /__|_| /
// \/ \/ \/
type ErrTeamAlreadyExist struct {
ID int64
OrgID int64
Name string
}
func IsErrTeamAlreadyExist(err error) bool {
_, ok := err.(ErrTeamAlreadyExist)
return ok
}
func (err ErrTeamAlreadyExist) Error() string {
return fmt.Sprintf("team already exists [id: %d, org_id: %d, name: %s]", err.ID, err.OrgID, err.Name)
}
// ____ ___ .__ .___
// | | \______ | | _________ __| _/
// | | /\____ \| | / _ \__ \ / __ |
// | | / | |_> > |_( <_> ) __ \_/ /_/ |
// |______/ | __/|____/\____(____ /\____ |
// |__| \/ \/
//
type ErrUploadNotExist struct {
ID int64
UUID string
}
func IsErrUploadNotExist(err error) bool {
_, ok := err.(ErrAttachmentNotExist)
return ok
}
func (err ErrUploadNotExist) Error() string {
return fmt.Sprintf("attachment does not exist [id: %d, uuid: %s]", err.ID, err.UUID)
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/notices_test.go | internal/database/notices_test.go | // Copyright 2023 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gorm.io/gorm"
)
func TestNotice_BeforeCreate(t *testing.T) {
now := time.Now()
db := &gorm.DB{
Config: &gorm.Config{
SkipDefaultTransaction: true,
NowFunc: func() time.Time {
return now
},
},
}
t.Run("CreatedUnix has been set", func(t *testing.T) {
notice := &Notice{
CreatedUnix: 1,
}
_ = notice.BeforeCreate(db)
assert.Equal(t, int64(1), notice.CreatedUnix)
})
t.Run("CreatedUnix has not been set", func(t *testing.T) {
notice := &Notice{}
_ = notice.BeforeCreate(db)
assert.Equal(t, db.NowFunc().Unix(), notice.CreatedUnix)
})
}
func TestNotice_AfterFind(t *testing.T) {
now := time.Now()
db := &gorm.DB{
Config: &gorm.Config{
SkipDefaultTransaction: true,
NowFunc: func() time.Time {
return now
},
},
}
notice := &Notice{
CreatedUnix: now.Unix(),
}
_ = notice.AfterFind(db)
assert.Equal(t, notice.CreatedUnix, notice.Created.Unix())
}
func TestNotices(t *testing.T) {
if testing.Short() {
t.Skip()
}
t.Parallel()
ctx := context.Background()
s := &NoticesStore{
db: newTestDB(t, "NoticesStore"),
}
for _, tc := range []struct {
name string
test func(t *testing.T, ctx context.Context, s *NoticesStore)
}{
{"Create", noticesCreate},
{"DeleteByIDs", noticesDeleteByIDs},
{"DeleteAll", noticesDeleteAll},
{"List", noticesList},
{"Count", noticesCount},
} {
t.Run(tc.name, func(t *testing.T) {
t.Cleanup(func() {
err := clearTables(t, s.db)
require.NoError(t, err)
})
tc.test(t, ctx, s)
})
if t.Failed() {
break
}
}
}
func noticesCreate(t *testing.T, ctx context.Context, s *NoticesStore) {
err := s.Create(ctx, NoticeTypeRepository, "test")
require.NoError(t, err)
count := s.Count(ctx)
assert.Equal(t, int64(1), count)
}
func noticesDeleteByIDs(t *testing.T, ctx context.Context, s *NoticesStore) {
err := s.Create(ctx, NoticeTypeRepository, "test")
require.NoError(t, err)
notices, err := s.List(ctx, 1, 10)
require.NoError(t, err)
ids := make([]int64, 0, len(notices))
for _, notice := range notices {
ids = append(ids, notice.ID)
}
// Non-existing IDs should be ignored
ids = append(ids, 404)
err = s.DeleteByIDs(ctx, ids...)
require.NoError(t, err)
count := s.Count(ctx)
assert.Equal(t, int64(0), count)
}
func noticesDeleteAll(t *testing.T, ctx context.Context, s *NoticesStore) {
err := s.Create(ctx, NoticeTypeRepository, "test")
require.NoError(t, err)
err = s.DeleteAll(ctx)
require.NoError(t, err)
count := s.Count(ctx)
assert.Equal(t, int64(0), count)
}
func noticesList(t *testing.T, ctx context.Context, s *NoticesStore) {
err := s.Create(ctx, NoticeTypeRepository, "test 1")
require.NoError(t, err)
err = s.Create(ctx, NoticeTypeRepository, "test 2")
require.NoError(t, err)
got1, err := s.List(ctx, 1, 1)
require.NoError(t, err)
require.Len(t, got1, 1)
got2, err := s.List(ctx, 2, 1)
require.NoError(t, err)
require.Len(t, got2, 1)
assert.True(t, got1[0].ID > got2[0].ID)
got, err := s.List(ctx, 1, 3)
require.NoError(t, err)
require.Len(t, got, 2)
}
func noticesCount(t *testing.T, ctx context.Context, s *NoticesStore) {
count := s.Count(ctx)
assert.Equal(t, int64(0), count)
err := s.Create(ctx, NoticeTypeRepository, "test")
require.NoError(t, err)
count = s.Count(ctx)
assert.Equal(t, int64(1), count)
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/issue_mail.go | internal/database/issue_mail.go | // Copyright 2016 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"context"
"fmt"
"github.com/pkg/errors"
"github.com/unknwon/com"
log "unknwon.dev/clog/v2"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/email"
"gogs.io/gogs/internal/markup"
"gogs.io/gogs/internal/userutil"
)
func (issue *Issue) MailSubject() string {
return fmt.Sprintf("[%s] %s (#%d)", issue.Repo.Name, issue.Title, issue.Index)
}
// mailerUser is a wrapper for satisfying mailer.User interface.
type mailerUser struct {
user *User
}
func (mu mailerUser) ID() int64 {
return mu.user.ID
}
func (mu mailerUser) DisplayName() string {
return mu.user.DisplayName()
}
func (mu mailerUser) Email() string {
return mu.user.Email
}
func (mu mailerUser) GenerateEmailActivateCode(email string) string {
return userutil.GenerateActivateCode(
mu.user.ID,
email,
mu.user.Name,
mu.user.Password,
mu.user.Rands,
)
}
func NewMailerUser(u *User) email.User {
return mailerUser{u}
}
// mailerRepo is a wrapper for satisfying mailer.Repository interface.
type mailerRepo struct {
repo *Repository
}
func (mr mailerRepo) FullName() string {
return mr.repo.FullName()
}
func (mr mailerRepo) HTMLURL() string {
return mr.repo.HTMLURL()
}
func (mr mailerRepo) ComposeMetas() map[string]string {
return mr.repo.ComposeMetas()
}
func NewMailerRepo(repo *Repository) email.Repository {
return mailerRepo{repo}
}
// mailerIssue is a wrapper for satisfying mailer.Issue interface.
type mailerIssue struct {
issue *Issue
}
func (mi mailerIssue) MailSubject() string {
return mi.issue.MailSubject()
}
func (mi mailerIssue) Content() string {
return mi.issue.Content
}
func (mi mailerIssue) HTMLURL() string {
return mi.issue.HTMLURL()
}
func NewMailerIssue(issue *Issue) email.Issue {
return mailerIssue{issue}
}
// mailIssueCommentToParticipants can be used for both new issue creation and comment.
// This functions sends two list of emails:
// 1. Repository watchers, users who participated in comments and the assignee.
// 2. Users who are not in 1. but get mentioned in current issue/comment.
func mailIssueCommentToParticipants(issue *Issue, doer *User, mentions []string) error {
ctx := context.TODO()
if !conf.User.EnableEmailNotification {
return nil
}
watchers, err := GetWatchers(issue.RepoID)
if err != nil {
return fmt.Errorf("GetWatchers [repo_id: %d]: %v", issue.RepoID, err)
}
participants, err := GetParticipantsByIssueID(issue.ID)
if err != nil {
return fmt.Errorf("GetParticipantsByIssueID [issue_id: %d]: %v", issue.ID, err)
}
// In case the issue poster is not watching the repository,
// even if we have duplicated in watchers, can be safely filtered out.
if issue.PosterID != doer.ID {
participants = append(participants, issue.Poster)
}
tos := make([]string, 0, len(watchers)) // List of email addresses
names := make([]string, 0, len(watchers))
for i := range watchers {
if watchers[i].UserID == doer.ID {
continue
}
to, err := Handle.Users().GetByID(ctx, watchers[i].UserID)
if err != nil {
return fmt.Errorf("GetUserByID [%d]: %v", watchers[i].UserID, err)
}
if to.IsOrganization() || !to.IsActive {
continue
}
tos = append(tos, to.Email)
names = append(names, to.Name)
}
for i := range participants {
if participants[i].ID == doer.ID {
continue
} else if com.IsSliceContainsStr(names, participants[i].Name) {
continue
}
tos = append(tos, participants[i].Email)
names = append(names, participants[i].Name)
}
if issue.Assignee != nil && issue.Assignee.ID != doer.ID {
if !com.IsSliceContainsStr(names, issue.Assignee.Name) {
tos = append(tos, issue.Assignee.Email)
names = append(names, issue.Assignee.Name)
}
}
email.SendIssueCommentMail(NewMailerIssue(issue), NewMailerRepo(issue.Repo), NewMailerUser(doer), tos)
// Mail mentioned people and exclude watchers.
names = append(names, doer.Name)
toUsernames := make([]string, 0, len(mentions)) // list of user names.
for i := range mentions {
if com.IsSliceContainsStr(names, mentions[i]) {
continue
}
toUsernames = append(toUsernames, mentions[i])
}
tos, err = Handle.Users().GetMailableEmailsByUsernames(ctx, toUsernames)
if err != nil {
return errors.Wrap(err, "get mailable emails by usernames")
}
email.SendIssueMentionMail(NewMailerIssue(issue), NewMailerRepo(issue.Repo), NewMailerUser(doer), tos)
return nil
}
// MailParticipants sends new issue thread created emails to repository watchers
// and mentioned people.
func (issue *Issue) MailParticipants() (err error) {
mentions := markup.FindAllMentions(issue.Content)
if err = updateIssueMentions(x, issue.ID, mentions); err != nil {
return fmt.Errorf("UpdateIssueMentions [%d]: %v", issue.ID, err)
}
if err = mailIssueCommentToParticipants(issue, issue.Poster, mentions); err != nil {
log.Error("mailIssueCommentToParticipants: %v", err)
}
return nil
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/ssh_key_test.go | internal/database/ssh_key_test.go | // Copyright 2016 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"testing"
"github.com/stretchr/testify/assert"
"gogs.io/gogs/internal/conf"
)
func Test_SSHParsePublicKey(t *testing.T) {
// TODO: Refactor SSHKeyGenParsePublicKey to accept a tempPath and remove this init.
conf.MustInit("")
tests := []struct {
name string
content string
expType string
expLength int
}{
{
name: "dsa-1024",
content: "ssh-dss AAAAB3NzaC1kc3MAAACBAOChCC7lf6Uo9n7BmZ6M8St19PZf4Tn59NriyboW2x/DZuYAz3ibZ2OkQ3S0SqDIa0HXSEJ1zaExQdmbO+Ux/wsytWZmCczWOVsaszBZSl90q8UnWlSH6P+/YA+RWJm5SFtuV9PtGIhyZgoNuz5kBQ7K139wuQsecdKktISwTakzAAAAFQCzKsO2JhNKlL+wwwLGOcLffoAmkwAAAIBpK7/3xvduajLBD/9vASqBQIHrgK2J+wiQnIb/Wzy0UsVmvfn8A+udRbBo+csM8xrSnlnlJnjkJS3qiM5g+eTwsLIV1IdKPEwmwB+VcP53Cw6lSyWyJcvhFb0N6s08NZysLzvj0N+ZC/FnhKTLzIyMtkHf/IrPCwlM+pV/M/96YgAAAIEAqQcGn9CKgzgPaguIZooTAOQdvBLMI5y0bQjOW6734XOpqQGf/Kra90wpoasLKZjSYKNPjE+FRUOrStLrxcNs4BeVKhy2PYTRnybfYVk1/dmKgH6P1YSRONsGKvTsH6c5IyCRG0ncCgYeF8tXppyd642982daopE7zQ/NPAnJfag= nocomment",
expType: "dsa",
expLength: 1024,
},
{
name: "rsa-1024",
content: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQDAu7tvIvX6ZHrRXuZNfkR3XLHSsuCK9Zn3X58lxBcQzuo5xZgB6vRwwm/QtJuF+zZPtY5hsQILBLmF+BZ5WpKZp1jBeSjH2G7lxet9kbcH+kIVj0tPFEoyKI9wvWqIwC4prx/WVk2wLTJjzBAhyNxfEq7C9CeiX9pQEbEqJfkKCQ== nocomment",
expType: "rsa",
expLength: 1024,
},
{
name: "rsa-2048",
content: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDMZXh+1OBUwSH9D45wTaxErQIN9IoC9xl7MKJkqvTvv6O5RR9YW/IK9FbfjXgXsppYGhsCZo1hFOOsXHMnfOORqu/xMDx4yPuyvKpw4LePEcg4TDipaDFuxbWOqc/BUZRZcXu41QAWfDLrInwsltWZHSeG7hjhpacl4FrVv9V1pS6Oc5Q1NxxEzTzuNLS/8diZrTm/YAQQ/+B+mzWI3zEtF4miZjjAljWd1LTBPvU23d29DcBmmFahcZ441XZsTeAwGxG/Q6j8NgNXj9WxMeWwxXV2jeAX/EBSpZrCVlCQ1yJswT6xCp8TuBnTiGWYMBNTbOZvPC4e0WI2/yZW/s5F nocomment",
expType: "rsa",
expLength: 2048,
},
{
name: "ecdsa-256",
content: "ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBFQacN3PrOll7PXmN5B/ZNVahiUIqI05nbBlZk1KXsO3d06ktAWqbNflv2vEmA38bTFTfJ2sbn2B5ksT52cDDbA= nocomment",
expType: "ecdsa",
expLength: 256,
},
{
name: "ecdsa-384",
content: "ecdsa-sha2-nistp384 AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBINmioV+XRX1Fm9Qk2ehHXJ2tfVxW30ypUWZw670Zyq5GQfBAH6xjygRsJ5wWsHXBsGYgFUXIHvMKVAG1tpw7s6ax9oA+dJOJ7tj+vhn8joFqT+sg3LYHgZkHrfqryRasQ== nocomment",
expType: "ecdsa",
expLength: 384,
},
{
name: "ecdsa-521",
content: "ecdsa-sha2-nistp521 AAAAE2VjZHNhLXNoYTItbmlzdHA1MjEAAAAIbmlzdHA1MjEAAACFBACGt3UG3EzRwNOI17QR84l6PgiAcvCE7v6aXPj/SC6UWKg4EL8vW9ZBcdYL9wzs4FZXh4MOV8jAzu3KRWNTwb4k2wFNUpGOt7l28MztFFEtH5BDDrtAJSPENPy8pvPLMfnPg5NhvWycqIBzNcHipem5wSJFN5PdpNOC2xMrPWKNqj+ZjQ== nocomment",
expType: "ecdsa",
expLength: 521,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
typ, length, err := SSHNativeParsePublicKey(test.content)
if err != nil {
t.Fatal(err)
}
assert.Equal(t, test.expType, typ)
assert.Equal(t, test.expLength, length)
typ, length, err = SSHKeyGenParsePublicKey(test.content)
if err != nil {
t.Fatal(err)
}
assert.Equal(t, test.expType, typ)
assert.Equal(t, test.expLength, length)
})
}
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/webhook_slack.go | internal/database/webhook_slack.go | // Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"fmt"
"strings"
jsoniter "github.com/json-iterator/go"
"github.com/pkg/errors"
"github.com/gogs/git-module"
api "github.com/gogs/go-gogs-client"
"gogs.io/gogs/internal/conf"
)
type SlackMeta struct {
Channel string `json:"channel"`
Username string `json:"username"`
IconURL string `json:"icon_url"`
Color string `json:"color"`
}
type SlackAttachment struct {
Fallback string `json:"fallback"`
Color string `json:"color"`
Title string `json:"title"`
Text string `json:"text"`
}
type SlackPayload struct {
Channel string `json:"channel"`
Text string `json:"text"`
Username string `json:"username"`
IconURL string `json:"icon_url"`
UnfurlLinks int `json:"unfurl_links"`
LinkNames int `json:"link_names"`
Attachments []*SlackAttachment `json:"attachments"`
}
func (p *SlackPayload) JSONPayload() ([]byte, error) {
data, err := jsoniter.MarshalIndent(p, "", " ")
if err != nil {
return []byte{}, err
}
return data, nil
}
// see: https://api.slack.com/docs/formatting
func SlackTextFormatter(s string) string {
// replace & < >
s = strings.ReplaceAll(s, "&", "&")
s = strings.ReplaceAll(s, "<", "<")
s = strings.ReplaceAll(s, ">", ">")
return s
}
func SlackShortTextFormatter(s string) string {
s = strings.Split(s, "\n")[0]
// replace & < >
s = strings.ReplaceAll(s, "&", "&")
s = strings.ReplaceAll(s, "<", "<")
s = strings.ReplaceAll(s, ">", ">")
return s
}
func SlackLinkFormatter(url, text string) string {
return fmt.Sprintf("<%s|%s>", url, SlackTextFormatter(text))
}
// getSlackCreatePayload composes Slack payload for create new branch or tag.
func getSlackCreatePayload(p *api.CreatePayload) *SlackPayload {
refName := git.RefShortName(p.Ref)
repoLink := SlackLinkFormatter(p.Repo.HTMLURL, p.Repo.Name)
refLink := SlackLinkFormatter(p.Repo.HTMLURL+"/src/"+refName, refName)
text := fmt.Sprintf("[%s:%s] %s created by %s", repoLink, refLink, p.RefType, p.Sender.UserName)
return &SlackPayload{
Text: text,
}
}
// getSlackDeletePayload composes Slack payload for delete a branch or tag.
func getSlackDeletePayload(p *api.DeletePayload) *SlackPayload {
refName := git.RefShortName(p.Ref)
repoLink := SlackLinkFormatter(p.Repo.HTMLURL, p.Repo.Name)
text := fmt.Sprintf("[%s:%s] %s deleted by %s", repoLink, refName, p.RefType, p.Sender.UserName)
return &SlackPayload{
Text: text,
}
}
// getSlackForkPayload composes Slack payload for forked by a repository.
func getSlackForkPayload(p *api.ForkPayload) *SlackPayload {
baseLink := SlackLinkFormatter(p.Repo.HTMLURL, p.Repo.Name)
forkLink := SlackLinkFormatter(p.Forkee.HTMLURL, p.Forkee.FullName)
text := fmt.Sprintf("%s is forked to %s", baseLink, forkLink)
return &SlackPayload{
Text: text,
}
}
func getSlackPushPayload(p *api.PushPayload, slack *SlackMeta) *SlackPayload {
// n new commits
var (
branchName = git.RefShortName(p.Ref)
commitDesc string
commitString string
)
if len(p.Commits) == 1 {
commitDesc = "1 new commit"
} else {
commitDesc = fmt.Sprintf("%d new commits", len(p.Commits))
}
if len(p.CompareURL) > 0 {
commitString = SlackLinkFormatter(p.CompareURL, commitDesc)
} else {
commitString = commitDesc
}
repoLink := SlackLinkFormatter(p.Repo.HTMLURL, p.Repo.Name)
branchLink := SlackLinkFormatter(p.Repo.HTMLURL+"/src/"+branchName, branchName)
text := fmt.Sprintf("[%s:%s] %s pushed by %s", repoLink, branchLink, commitString, p.Pusher.UserName)
var attachmentText string
// for each commit, generate attachment text
for i, commit := range p.Commits {
attachmentText += fmt.Sprintf("%s: %s - %s", SlackLinkFormatter(commit.URL, commit.ID[:7]), SlackShortTextFormatter(commit.Message), SlackTextFormatter(commit.Author.Name))
// add linebreak to each commit but the last
if i < len(p.Commits)-1 {
attachmentText += "\n"
}
}
return &SlackPayload{
Channel: slack.Channel,
Text: text,
Username: slack.Username,
IconURL: slack.IconURL,
Attachments: []*SlackAttachment{{
Color: slack.Color,
Text: attachmentText,
}},
}
}
func getSlackIssuesPayload(p *api.IssuesPayload, slack *SlackMeta) *SlackPayload {
senderLink := SlackLinkFormatter(conf.Server.ExternalURL+p.Sender.UserName, p.Sender.UserName)
titleLink := SlackLinkFormatter(fmt.Sprintf("%s/issues/%d", p.Repository.HTMLURL, p.Index),
fmt.Sprintf("#%d %s", p.Index, p.Issue.Title))
var text, title, attachmentText string
switch p.Action {
case api.HOOK_ISSUE_OPENED:
text = fmt.Sprintf("[%s] New issue created by %s", p.Repository.FullName, senderLink)
title = titleLink
attachmentText = SlackTextFormatter(p.Issue.Body)
case api.HOOK_ISSUE_CLOSED:
text = fmt.Sprintf("[%s] Issue closed: %s by %s", p.Repository.FullName, titleLink, senderLink)
case api.HOOK_ISSUE_REOPENED:
text = fmt.Sprintf("[%s] Issue re-opened: %s by %s", p.Repository.FullName, titleLink, senderLink)
case api.HOOK_ISSUE_EDITED:
text = fmt.Sprintf("[%s] Issue edited: %s by %s", p.Repository.FullName, titleLink, senderLink)
attachmentText = SlackTextFormatter(p.Issue.Body)
case api.HOOK_ISSUE_ASSIGNED:
text = fmt.Sprintf("[%s] Issue assigned to %s: %s by %s", p.Repository.FullName,
SlackLinkFormatter(conf.Server.ExternalURL+p.Issue.Assignee.UserName, p.Issue.Assignee.UserName),
titleLink, senderLink)
case api.HOOK_ISSUE_UNASSIGNED:
text = fmt.Sprintf("[%s] Issue unassigned: %s by %s", p.Repository.FullName, titleLink, senderLink)
case api.HOOK_ISSUE_LABEL_UPDATED:
text = fmt.Sprintf("[%s] Issue labels updated: %s by %s", p.Repository.FullName, titleLink, senderLink)
case api.HOOK_ISSUE_LABEL_CLEARED:
text = fmt.Sprintf("[%s] Issue labels cleared: %s by %s", p.Repository.FullName, titleLink, senderLink)
case api.HOOK_ISSUE_MILESTONED:
text = fmt.Sprintf("[%s] Issue milestoned: %s by %s", p.Repository.FullName, titleLink, senderLink)
case api.HOOK_ISSUE_DEMILESTONED:
text = fmt.Sprintf("[%s] Issue demilestoned: %s by %s", p.Repository.FullName, titleLink, senderLink)
}
return &SlackPayload{
Channel: slack.Channel,
Text: text,
Username: slack.Username,
IconURL: slack.IconURL,
Attachments: []*SlackAttachment{{
Color: slack.Color,
Title: title,
Text: attachmentText,
}},
}
}
func getSlackIssueCommentPayload(p *api.IssueCommentPayload, slack *SlackMeta) *SlackPayload {
senderLink := SlackLinkFormatter(conf.Server.ExternalURL+p.Sender.UserName, p.Sender.UserName)
titleLink := SlackLinkFormatter(fmt.Sprintf("%s/issues/%d#%s", p.Repository.HTMLURL, p.Issue.Index, CommentHashTag(p.Comment.ID)),
fmt.Sprintf("#%d %s", p.Issue.Index, p.Issue.Title))
var text, title, attachmentText string
switch p.Action {
case api.HOOK_ISSUE_COMMENT_CREATED:
text = fmt.Sprintf("[%s] New comment created by %s", p.Repository.FullName, senderLink)
title = titleLink
attachmentText = SlackTextFormatter(p.Comment.Body)
case api.HOOK_ISSUE_COMMENT_EDITED:
text = fmt.Sprintf("[%s] Comment edited by %s", p.Repository.FullName, senderLink)
title = titleLink
attachmentText = SlackTextFormatter(p.Comment.Body)
case api.HOOK_ISSUE_COMMENT_DELETED:
text = fmt.Sprintf("[%s] Comment deleted by %s", p.Repository.FullName, senderLink)
title = SlackLinkFormatter(fmt.Sprintf("%s/issues/%d", p.Repository.HTMLURL, p.Issue.Index),
fmt.Sprintf("#%d %s", p.Issue.Index, p.Issue.Title))
attachmentText = SlackTextFormatter(p.Comment.Body)
}
return &SlackPayload{
Channel: slack.Channel,
Text: text,
Username: slack.Username,
IconURL: slack.IconURL,
Attachments: []*SlackAttachment{{
Color: slack.Color,
Title: title,
Text: attachmentText,
}},
}
}
func getSlackPullRequestPayload(p *api.PullRequestPayload, slack *SlackMeta) *SlackPayload {
senderLink := SlackLinkFormatter(conf.Server.ExternalURL+p.Sender.UserName, p.Sender.UserName)
titleLink := SlackLinkFormatter(fmt.Sprintf("%s/pulls/%d", p.Repository.HTMLURL, p.Index),
fmt.Sprintf("#%d %s", p.Index, p.PullRequest.Title))
var text, title, attachmentText string
switch p.Action {
case api.HOOK_ISSUE_OPENED:
text = fmt.Sprintf("[%s] Pull request submitted by %s", p.Repository.FullName, senderLink)
title = titleLink
attachmentText = SlackTextFormatter(p.PullRequest.Body)
case api.HOOK_ISSUE_CLOSED:
if p.PullRequest.HasMerged {
text = fmt.Sprintf("[%s] Pull request merged: %s by %s", p.Repository.FullName, titleLink, senderLink)
} else {
text = fmt.Sprintf("[%s] Pull request closed: %s by %s", p.Repository.FullName, titleLink, senderLink)
}
case api.HOOK_ISSUE_REOPENED:
text = fmt.Sprintf("[%s] Pull request re-opened: %s by %s", p.Repository.FullName, titleLink, senderLink)
case api.HOOK_ISSUE_EDITED:
text = fmt.Sprintf("[%s] Pull request edited: %s by %s", p.Repository.FullName, titleLink, senderLink)
attachmentText = SlackTextFormatter(p.PullRequest.Body)
case api.HOOK_ISSUE_ASSIGNED:
text = fmt.Sprintf("[%s] Pull request assigned to %s: %s by %s", p.Repository.FullName,
SlackLinkFormatter(conf.Server.ExternalURL+p.PullRequest.Assignee.UserName, p.PullRequest.Assignee.UserName),
titleLink, senderLink)
case api.HOOK_ISSUE_UNASSIGNED:
text = fmt.Sprintf("[%s] Pull request unassigned: %s by %s", p.Repository.FullName, titleLink, senderLink)
case api.HOOK_ISSUE_LABEL_UPDATED:
text = fmt.Sprintf("[%s] Pull request labels updated: %s by %s", p.Repository.FullName, titleLink, senderLink)
case api.HOOK_ISSUE_LABEL_CLEARED:
text = fmt.Sprintf("[%s] Pull request labels cleared: %s by %s", p.Repository.FullName, titleLink, senderLink)
case api.HOOK_ISSUE_SYNCHRONIZED:
text = fmt.Sprintf("[%s] Pull request synchronized: %s by %s", p.Repository.FullName, titleLink, senderLink)
case api.HOOK_ISSUE_MILESTONED:
text = fmt.Sprintf("[%s] Pull request milestoned: %s by %s", p.Repository.FullName, titleLink, senderLink)
case api.HOOK_ISSUE_DEMILESTONED:
text = fmt.Sprintf("[%s] Pull request demilestoned: %s by %s", p.Repository.FullName, titleLink, senderLink)
}
return &SlackPayload{
Channel: slack.Channel,
Text: text,
Username: slack.Username,
IconURL: slack.IconURL,
Attachments: []*SlackAttachment{{
Color: slack.Color,
Title: title,
Text: attachmentText,
}},
}
}
func getSlackReleasePayload(p *api.ReleasePayload) *SlackPayload {
repoLink := SlackLinkFormatter(p.Repository.HTMLURL, p.Repository.Name)
refLink := SlackLinkFormatter(p.Repository.HTMLURL+"/src/"+p.Release.TagName, p.Release.TagName)
text := fmt.Sprintf("[%s] new release %s published by %s", repoLink, refLink, p.Sender.UserName)
return &SlackPayload{
Text: text,
}
}
func GetSlackPayload(p api.Payloader, event HookEventType, meta string) (payload *SlackPayload, err error) {
slack := &SlackMeta{}
if err := jsoniter.Unmarshal([]byte(meta), &slack); err != nil {
return nil, fmt.Errorf("unmarshal: %v", err)
}
switch event {
case HookEventTypeCreate:
payload = getSlackCreatePayload(p.(*api.CreatePayload))
case HookEventTypeDelete:
payload = getSlackDeletePayload(p.(*api.DeletePayload))
case HookEventTypeFork:
payload = getSlackForkPayload(p.(*api.ForkPayload))
case HookEventTypePush:
payload = getSlackPushPayload(p.(*api.PushPayload), slack)
case HookEventTypeIssues:
payload = getSlackIssuesPayload(p.(*api.IssuesPayload), slack)
case HookEventTypeIssueComment:
payload = getSlackIssueCommentPayload(p.(*api.IssueCommentPayload), slack)
case HookEventTypePullRequest:
payload = getSlackPullRequestPayload(p.(*api.PullRequestPayload), slack)
case HookEventTypeRelease:
payload = getSlackReleasePayload(p.(*api.ReleasePayload))
default:
return nil, errors.Errorf("unexpected event %q", event)
}
payload.Channel = slack.Channel
payload.Username = slack.Username
payload.IconURL = slack.IconURL
if len(payload.Attachments) > 0 {
payload.Attachments[0].Color = slack.Color
}
return payload, nil
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/two_factors_test.go | internal/database/two_factors_test.go | // Copyright 2020 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gorm.io/gorm"
"gogs.io/gogs/internal/errutil"
)
func TestTwoFactor_BeforeCreate(t *testing.T) {
now := time.Now()
db := &gorm.DB{
Config: &gorm.Config{
SkipDefaultTransaction: true,
NowFunc: func() time.Time {
return now
},
},
}
t.Run("CreatedUnix has been set", func(t *testing.T) {
tf := &TwoFactor{
CreatedUnix: 1,
}
_ = tf.BeforeCreate(db)
assert.Equal(t, int64(1), tf.CreatedUnix)
})
t.Run("CreatedUnix has not been set", func(t *testing.T) {
tf := &TwoFactor{}
_ = tf.BeforeCreate(db)
assert.Equal(t, db.NowFunc().Unix(), tf.CreatedUnix)
})
}
func TestTwoFactor_AfterFind(t *testing.T) {
now := time.Now()
db := &gorm.DB{
Config: &gorm.Config{
SkipDefaultTransaction: true,
NowFunc: func() time.Time {
return now
},
},
}
tf := &TwoFactor{
CreatedUnix: now.Unix(),
}
_ = tf.AfterFind(db)
assert.Equal(t, tf.CreatedUnix, tf.Created.Unix())
}
func TestTwoFactors(t *testing.T) {
if testing.Short() {
t.Skip()
}
t.Parallel()
ctx := context.Background()
s := &TwoFactorsStore{
db: newTestDB(t, "TwoFactorsStore"),
}
for _, tc := range []struct {
name string
test func(t *testing.T, ctx context.Context, s *TwoFactorsStore)
}{
{"Create", twoFactorsCreate},
{"GetByUserID", twoFactorsGetByUserID},
{"IsEnabled", twoFactorsIsEnabled},
} {
t.Run(tc.name, func(t *testing.T) {
t.Cleanup(func() {
err := clearTables(t, s.db)
require.NoError(t, err)
})
tc.test(t, ctx, s)
})
if t.Failed() {
break
}
}
}
func twoFactorsCreate(t *testing.T, ctx context.Context, s *TwoFactorsStore) {
// Create a 2FA token
err := s.Create(ctx, 1, "secure-key", "secure-secret")
require.NoError(t, err)
// Get it back and check the Created field
tf, err := s.GetByUserID(ctx, 1)
require.NoError(t, err)
assert.Equal(t, s.db.NowFunc().Format(time.RFC3339), tf.Created.UTC().Format(time.RFC3339))
// Verify there are 10 recover codes generated
var count int64
err = s.db.Model(new(TwoFactorRecoveryCode)).Count(&count).Error
require.NoError(t, err)
assert.Equal(t, int64(10), count)
}
func twoFactorsGetByUserID(t *testing.T, ctx context.Context, s *TwoFactorsStore) {
// Create a 2FA token for user 1
err := s.Create(ctx, 1, "secure-key", "secure-secret")
require.NoError(t, err)
// We should be able to get it back
_, err = s.GetByUserID(ctx, 1)
require.NoError(t, err)
// Try to get a non-existent 2FA token
_, err = s.GetByUserID(ctx, 2)
wantErr := ErrTwoFactorNotFound{args: errutil.Args{"userID": int64(2)}}
assert.Equal(t, wantErr, err)
}
func twoFactorsIsEnabled(t *testing.T, ctx context.Context, s *TwoFactorsStore) {
// Create a 2FA token for user 1
err := s.Create(ctx, 1, "secure-key", "secure-secret")
require.NoError(t, err)
assert.True(t, s.IsEnabled(ctx, 1))
assert.False(t, s.IsEnabled(ctx, 2))
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/attachment.go | internal/database/attachment.go | // Copyright 2017 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"fmt"
"io"
"mime/multipart"
"os"
"path"
"time"
gouuid "github.com/satori/go.uuid"
"xorm.io/xorm"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/errutil"
)
// Attachment represent a attachment of issue/comment/release.
type Attachment struct {
ID int64
UUID string `xorm:"uuid UNIQUE"`
IssueID int64 `xorm:"INDEX"`
CommentID int64
ReleaseID int64 `xorm:"INDEX"`
Name string
Created time.Time `xorm:"-" json:"-" gorm:"-"`
CreatedUnix int64
}
func (a *Attachment) BeforeInsert() {
a.CreatedUnix = time.Now().Unix()
}
func (a *Attachment) AfterSet(colName string, _ xorm.Cell) {
switch colName {
case "created_unix":
a.Created = time.Unix(a.CreatedUnix, 0).Local()
}
}
// AttachmentLocalPath returns where attachment is stored in local file system based on given UUID.
func AttachmentLocalPath(uuid string) string {
return path.Join(conf.Attachment.Path, uuid[0:1], uuid[1:2], uuid)
}
// LocalPath returns where attachment is stored in local file system.
func (a *Attachment) LocalPath() string {
return AttachmentLocalPath(a.UUID)
}
// NewAttachment creates a new attachment object.
func NewAttachment(name string, buf []byte, file multipart.File) (_ *Attachment, err error) {
attach := &Attachment{
UUID: gouuid.NewV4().String(),
Name: name,
}
localPath := attach.LocalPath()
if err = os.MkdirAll(path.Dir(localPath), os.ModePerm); err != nil {
return nil, fmt.Errorf("MkdirAll: %v", err)
}
fw, err := os.Create(localPath)
if err != nil {
return nil, fmt.Errorf("Create: %v", err)
}
defer fw.Close()
if _, err = fw.Write(buf); err != nil {
return nil, fmt.Errorf("write: %v", err)
} else if _, err = io.Copy(fw, file); err != nil {
return nil, fmt.Errorf("copy: %v", err)
}
if _, err := x.Insert(attach); err != nil {
return nil, err
}
return attach, nil
}
var _ errutil.NotFound = (*ErrAttachmentNotExist)(nil)
type ErrAttachmentNotExist struct {
args map[string]any
}
func IsErrAttachmentNotExist(err error) bool {
_, ok := err.(ErrAttachmentNotExist)
return ok
}
func (err ErrAttachmentNotExist) Error() string {
return fmt.Sprintf("attachment does not exist: %v", err.args)
}
func (ErrAttachmentNotExist) NotFound() bool {
return true
}
func getAttachmentByUUID(e Engine, uuid string) (*Attachment, error) {
attach := &Attachment{UUID: uuid}
has, err := e.Get(attach)
if err != nil {
return nil, err
} else if !has {
return nil, ErrAttachmentNotExist{args: map[string]any{"uuid": uuid}}
}
return attach, nil
}
func getAttachmentsByUUIDs(e Engine, uuids []string) ([]*Attachment, error) {
if len(uuids) == 0 {
return []*Attachment{}, nil
}
// Silently drop invalid uuids.
attachments := make([]*Attachment, 0, len(uuids))
return attachments, e.In("uuid", uuids).Find(&attachments)
}
// GetAttachmentByUUID returns attachment by given UUID.
func GetAttachmentByUUID(uuid string) (*Attachment, error) {
return getAttachmentByUUID(x, uuid)
}
func getAttachmentsByIssueID(e Engine, issueID int64) ([]*Attachment, error) {
attachments := make([]*Attachment, 0, 5)
return attachments, e.Where("issue_id = ? AND comment_id = 0", issueID).Find(&attachments)
}
// GetAttachmentsByIssueID returns all attachments of an issue.
func GetAttachmentsByIssueID(issueID int64) ([]*Attachment, error) {
return getAttachmentsByIssueID(x, issueID)
}
func getAttachmentsByCommentID(e Engine, commentID int64) ([]*Attachment, error) {
attachments := make([]*Attachment, 0, 5)
return attachments, e.Where("comment_id=?", commentID).Find(&attachments)
}
// GetAttachmentsByCommentID returns all attachments of a comment.
func GetAttachmentsByCommentID(commentID int64) ([]*Attachment, error) {
return getAttachmentsByCommentID(x, commentID)
}
func getAttachmentsByReleaseID(e Engine, releaseID int64) ([]*Attachment, error) {
attachments := make([]*Attachment, 0, 10)
return attachments, e.Where("release_id = ?", releaseID).Find(&attachments)
}
// GetAttachmentsByReleaseID returns all attachments of a release.
func GetAttachmentsByReleaseID(releaseID int64) ([]*Attachment, error) {
return getAttachmentsByReleaseID(x, releaseID)
}
// DeleteAttachment deletes the given attachment and optionally the associated file.
func DeleteAttachment(a *Attachment, remove bool) error {
_, err := DeleteAttachments([]*Attachment{a}, remove)
return err
}
// DeleteAttachments deletes the given attachments and optionally the associated files.
func DeleteAttachments(attachments []*Attachment, remove bool) (int, error) {
for i, a := range attachments {
if remove {
if err := os.Remove(a.LocalPath()); err != nil {
return i, err
}
}
if _, err := x.Delete(a); err != nil {
return i, err
}
}
return len(attachments), nil
}
// DeleteAttachmentsByIssue deletes all attachments associated with the given issue.
func DeleteAttachmentsByIssue(issueID int64, remove bool) (int, error) {
attachments, err := GetAttachmentsByIssueID(issueID)
if err != nil {
return 0, err
}
return DeleteAttachments(attachments, remove)
}
// DeleteAttachmentsByComment deletes all attachments associated with the given comment.
func DeleteAttachmentsByComment(commentID int64, remove bool) (int, error) {
attachments, err := GetAttachmentsByCommentID(commentID)
if err != nil {
return 0, err
}
return DeleteAttachments(attachments, remove)
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/ssh_key.go | internal/database/ssh_key.go | // Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"context"
"encoding/base64"
"encoding/binary"
"errors"
"fmt"
"math/big"
"os"
"path"
"path/filepath"
"strings"
"sync"
"time"
"github.com/unknwon/com"
"golang.org/x/crypto/ssh"
log "unknwon.dev/clog/v2"
"xorm.io/xorm"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/errutil"
"gogs.io/gogs/internal/process"
)
const (
tplPublicKey = `command="%s serv key-%d --config='%s'",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty %s` + "\n"
)
var sshOpLocker sync.Mutex
type KeyType int
const (
KeyTypeUser = iota + 1
KeyTypeDeploy
)
// PublicKey represents a user or deploy SSH public key.
type PublicKey struct {
ID int64 `gorm:"primaryKey"`
OwnerID int64 `xorm:"INDEX NOT NULL" gorm:"index;not null"`
Name string `xorm:"NOT NULL" gorm:"not null"`
Fingerprint string `xorm:"NOT NULL" gorm:"not null"`
Content string `xorm:"TEXT NOT NULL" gorm:"type:TEXT;not null"`
Mode AccessMode `xorm:"NOT NULL DEFAULT 2" gorm:"not null;default:2"`
Type KeyType `xorm:"NOT NULL DEFAULT 1" gorm:"not null;default:1"`
Created time.Time `xorm:"-" json:"-" gorm:"-"`
CreatedUnix int64
Updated time.Time `xorm:"-" json:"-" gorm:"-"` // Note: Updated must below Created for AfterSet.
UpdatedUnix int64
HasRecentActivity bool `xorm:"-" json:"-" gorm:"-"`
HasUsed bool `xorm:"-" json:"-" gorm:"-"`
}
func (k *PublicKey) BeforeInsert() {
k.CreatedUnix = time.Now().Unix()
}
func (k *PublicKey) BeforeUpdate() {
k.UpdatedUnix = time.Now().Unix()
}
func (k *PublicKey) AfterSet(colName string, _ xorm.Cell) {
switch colName {
case "created_unix":
k.Created = time.Unix(k.CreatedUnix, 0).Local()
case "updated_unix":
k.Updated = time.Unix(k.UpdatedUnix, 0).Local()
k.HasUsed = k.Updated.After(k.Created)
k.HasRecentActivity = k.Updated.Add(7 * 24 * time.Hour).After(time.Now())
}
}
// OmitEmail returns content of public key without email address.
func (k *PublicKey) OmitEmail() string {
return strings.Join(strings.Split(k.Content, " ")[:2], " ")
}
// AuthorizedString returns formatted public key string for authorized_keys file.
func (k *PublicKey) AuthorizedString() string {
return fmt.Sprintf(tplPublicKey, conf.AppPath(), k.ID, conf.CustomConf, k.Content)
}
// IsDeployKey returns true if the public key is used as deploy key.
func (k *PublicKey) IsDeployKey() bool {
return k.Type == KeyTypeDeploy
}
func extractTypeFromBase64Key(key string) (string, error) {
b, err := base64.StdEncoding.DecodeString(key)
if err != nil || len(b) < 4 {
return "", fmt.Errorf("invalid key format: %v", err)
}
keyLength := int(binary.BigEndian.Uint32(b))
if len(b) < 4+keyLength {
return "", fmt.Errorf("invalid key format: not enough length %d", keyLength)
}
return string(b[4 : 4+keyLength]), nil
}
// parseKeyString parses any key string in OpenSSH or SSH2 format to clean OpenSSH string (RFC4253).
func parseKeyString(content string) (string, error) {
// Transform all legal line endings to a single "\n"
// Replace all windows full new lines ("\r\n")
content = strings.ReplaceAll(content, "\r\n", "\n")
// Replace all windows half new lines ("\r"), if it happen not to match replace above
content = strings.ReplaceAll(content, "\r", "\n")
// Replace ending new line as its may cause unwanted behaviour (extra line means not a single line key | OpenSSH key)
content = strings.TrimRight(content, "\n")
// split lines
lines := strings.Split(content, "\n")
var keyType, keyContent, keyComment string
if len(lines) == 1 {
// Parse OpenSSH format.
parts := strings.SplitN(lines[0], " ", 3)
switch len(parts) {
case 0:
return "", errors.New("empty key")
case 1:
keyContent = parts[0]
case 2:
keyType = parts[0]
keyContent = parts[1]
default:
keyType = parts[0]
keyContent = parts[1]
keyComment = parts[2]
}
// If keyType is not given, extract it from content. If given, validate it.
t, err := extractTypeFromBase64Key(keyContent)
if err != nil {
return "", fmt.Errorf("extractTypeFromBase64Key: %v", err)
}
if keyType == "" {
keyType = t
} else if keyType != t {
return "", fmt.Errorf("key type and content does not match: %s - %s", keyType, t)
}
} else {
// Parse SSH2 file format.
continuationLine := false
for _, line := range lines {
// Skip lines that:
// 1) are a continuation of the previous line,
// 2) contain ":" as that are comment lines
// 3) contain "-" as that are begin and end tags
if continuationLine || strings.ContainsAny(line, ":-") {
continuationLine = strings.HasSuffix(line, "\\")
} else {
keyContent = keyContent + line
}
}
t, err := extractTypeFromBase64Key(keyContent)
if err != nil {
return "", fmt.Errorf("extractTypeFromBase64Key: %v", err)
}
keyType = t
}
return keyType + " " + keyContent + " " + keyComment, nil
}
// writeTmpKeyFile writes key content to a temporary file
// and returns the name of that file, along with any possible errors.
func writeTmpKeyFile(content string) (string, error) {
tmpFile, err := os.CreateTemp(conf.SSH.KeyTestPath, "gogs_keytest")
if err != nil {
return "", fmt.Errorf("TempFile: %v", err)
}
defer tmpFile.Close()
if _, err = tmpFile.WriteString(content); err != nil {
return "", fmt.Errorf("WriteString: %v", err)
}
return tmpFile.Name(), nil
}
// SSHKeyGenParsePublicKey extracts key type and length using ssh-keygen.
func SSHKeyGenParsePublicKey(key string) (string, int, error) {
tmpName, err := writeTmpKeyFile(key)
if err != nil {
return "", 0, fmt.Errorf("writeTmpKeyFile: %v", err)
}
defer os.Remove(tmpName)
stdout, stderr, err := process.Exec("SSHKeyGenParsePublicKey", conf.SSH.KeygenPath, "-lf", tmpName)
if err != nil {
return "", 0, fmt.Errorf("fail to parse public key: %s - %s", err, stderr)
}
if strings.Contains(stdout, "is not a public key file") {
return "", 0, ErrKeyUnableVerify{stdout}
}
fields := strings.Split(stdout, " ")
if len(fields) < 4 {
return "", 0, fmt.Errorf("invalid public key line: %s", stdout)
}
keyType := strings.Trim(fields[len(fields)-1], "()\r\n")
return strings.ToLower(keyType), com.StrTo(fields[0]).MustInt(), nil
}
// SSHNativeParsePublicKey extracts the key type and length using the golang SSH library.
func SSHNativeParsePublicKey(keyLine string) (string, int, error) {
fields := strings.Fields(keyLine)
if len(fields) < 2 {
return "", 0, fmt.Errorf("not enough fields in public key line: %s", keyLine)
}
raw, err := base64.StdEncoding.DecodeString(fields[1])
if err != nil {
return "", 0, err
}
pkey, err := ssh.ParsePublicKey(raw)
if err != nil {
if strings.Contains(err.Error(), "ssh: unknown key algorithm") {
return "", 0, ErrKeyUnableVerify{err.Error()}
}
return "", 0, fmt.Errorf("ParsePublicKey: %v", err)
}
// The ssh library can parse the key, so next we find out what key exactly we have.
switch pkey.Type() {
case ssh.KeyAlgoDSA:
rawPub := struct {
Name string
P, Q, G, Y *big.Int
}{}
if err := ssh.Unmarshal(pkey.Marshal(), &rawPub); err != nil {
return "", 0, err
}
// as per https://bugzilla.mindrot.org/show_bug.cgi?id=1647 we should never
// see dsa keys != 1024 bit, but as it seems to work, we will not check here
return "dsa", rawPub.P.BitLen(), nil // use P as per crypto/dsa/dsa.go (is L)
case ssh.KeyAlgoRSA:
rawPub := struct {
Name string
E *big.Int
N *big.Int
}{}
if err := ssh.Unmarshal(pkey.Marshal(), &rawPub); err != nil {
return "", 0, err
}
return "rsa", rawPub.N.BitLen(), nil // use N as per crypto/rsa/rsa.go (is bits)
case ssh.KeyAlgoECDSA256:
return "ecdsa", 256, nil
case ssh.KeyAlgoECDSA384:
return "ecdsa", 384, nil
case ssh.KeyAlgoECDSA521:
return "ecdsa", 521, nil
case ssh.KeyAlgoED25519:
return "ed25519", 256, nil
}
return "", 0, fmt.Errorf("unsupported key length detection for type: %s", pkey.Type())
}
// CheckPublicKeyString checks if the given public key string is recognized by SSH.
// It returns the actual public key line on success.
func CheckPublicKeyString(content string) (_ string, err error) {
if conf.SSH.Disabled {
return "", errors.New("SSH is disabled")
}
content, err = parseKeyString(content)
if err != nil {
return "", err
}
content = strings.TrimRight(content, "\n\r")
if strings.ContainsAny(content, "\n\r") {
return "", errors.New("only a single line with a single key please")
}
// Remove any unnecessary whitespace
content = strings.TrimSpace(content)
if !conf.SSH.MinimumKeySizeCheck {
return content, nil
}
var (
fnName string
keyType string
length int
)
if conf.SSH.StartBuiltinServer {
fnName = "SSHNativeParsePublicKey"
keyType, length, err = SSHNativeParsePublicKey(content)
} else {
fnName = "SSHKeyGenParsePublicKey"
keyType, length, err = SSHKeyGenParsePublicKey(content)
}
if err != nil {
return "", fmt.Errorf("%s: %v", fnName, err)
}
log.Trace("Key info [native: %v]: %s-%d", conf.SSH.StartBuiltinServer, keyType, length)
if minLen, found := conf.SSH.MinimumKeySizes[keyType]; found && length >= minLen {
return content, nil
} else if found && length < minLen {
return "", fmt.Errorf("key length is not enough: got %d, needs %d", length, minLen)
}
return "", fmt.Errorf("key type is not allowed: %s", keyType)
}
// appendAuthorizedKeysToFile appends new SSH keys' content to authorized_keys file.
func appendAuthorizedKeysToFile(keys ...*PublicKey) error {
sshOpLocker.Lock()
defer sshOpLocker.Unlock()
fpath := filepath.Join(conf.SSH.RootPath, "authorized_keys")
f, err := os.OpenFile(fpath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
if err != nil {
return err
}
defer f.Close()
// Note: chmod command does not support in Windows.
if !conf.IsWindowsRuntime() {
fi, err := f.Stat()
if err != nil {
return err
}
// .ssh directory should have mode 700, and authorized_keys file should have mode 600.
if fi.Mode().Perm() > 0600 {
log.Error("authorized_keys file has unusual permission flags: %s - setting to -rw-------", fi.Mode().Perm().String())
if err = f.Chmod(0600); err != nil {
return err
}
}
}
for _, key := range keys {
if _, err = f.WriteString(key.AuthorizedString()); err != nil {
return err
}
}
return nil
}
// checkKeyContent onlys checks if key content has been used as public key,
// it is OK to use same key as deploy key for multiple repositories/users.
func checkKeyContent(content string) error {
has, err := x.Get(&PublicKey{
Content: content,
Type: KeyTypeUser,
})
if err != nil {
return err
} else if has {
return ErrKeyAlreadyExist{0, content}
}
return nil
}
func addKey(e Engine, key *PublicKey) (err error) {
// Calculate fingerprint.
tmpPath := strings.ReplaceAll(path.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()), "id_rsa.pub"), "\\", "/")
_ = os.MkdirAll(path.Dir(tmpPath), os.ModePerm)
if err = os.WriteFile(tmpPath, []byte(key.Content), 0644); err != nil {
return err
}
stdout, stderr, err := process.Exec("AddPublicKey", conf.SSH.KeygenPath, "-lf", tmpPath)
if err != nil {
return fmt.Errorf("fail to parse public key: %s - %s", err, stderr)
} else if len(stdout) < 2 {
return errors.New("not enough output for calculating fingerprint: " + stdout)
}
key.Fingerprint = strings.Split(stdout, " ")[1]
// Save SSH key.
if _, err = e.Insert(key); err != nil {
return err
}
// Don't need to rewrite this file if builtin SSH server is enabled.
if conf.SSH.StartBuiltinServer {
return nil
}
return appendAuthorizedKeysToFile(key)
}
// AddPublicKey adds new public key to database and authorized_keys file.
func AddPublicKey(ownerID int64, name, content string) (*PublicKey, error) {
log.Trace("Add public key: %s", content)
if err := checkKeyContent(content); err != nil {
return nil, err
}
// Key name of same user cannot be duplicated.
has, err := x.Where("owner_id = ? AND name = ?", ownerID, name).Get(new(PublicKey))
if err != nil {
return nil, err
} else if has {
return nil, ErrKeyNameAlreadyUsed{ownerID, name}
}
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return nil, err
}
key := &PublicKey{
OwnerID: ownerID,
Name: name,
Content: content,
Mode: AccessModeWrite,
Type: KeyTypeUser,
}
if err = addKey(sess, key); err != nil {
return nil, fmt.Errorf("addKey: %v", err)
}
return key, sess.Commit()
}
// GetPublicKeyByID returns public key by given ID.
func GetPublicKeyByID(keyID int64) (*PublicKey, error) {
key := new(PublicKey)
has, err := x.Id(keyID).Get(key)
if err != nil {
return nil, err
} else if !has {
return nil, ErrKeyNotExist{keyID}
}
return key, nil
}
// SearchPublicKeyByContent searches a public key using the content as prefix
// (i.e. ignore the email part). It returns ErrKeyNotExist if no such key
// exists.
func SearchPublicKeyByContent(content string) (*PublicKey, error) {
key := new(PublicKey)
has, err := x.Where("content like ?", content+"%").Get(key)
if err != nil {
return nil, err
} else if !has {
return nil, ErrKeyNotExist{}
}
return key, nil
}
// ListPublicKeys returns a list of public keys belongs to given user.
func ListPublicKeys(uid int64) ([]*PublicKey, error) {
keys := make([]*PublicKey, 0, 5)
return keys, x.Where("owner_id = ?", uid).Find(&keys)
}
// UpdatePublicKey updates given public key.
func UpdatePublicKey(key *PublicKey) error {
_, err := x.Id(key.ID).AllCols().Update(key)
return err
}
// deletePublicKeys does the actual key deletion but does not update authorized_keys file.
func deletePublicKeys(e *xorm.Session, keyIDs ...int64) error {
if len(keyIDs) == 0 {
return nil
}
_, err := e.In("id", keyIDs).Delete(new(PublicKey))
return err
}
// DeletePublicKey deletes SSH key information both in database and authorized_keys file.
func DeletePublicKey(doer *User, id int64) (err error) {
key, err := GetPublicKeyByID(id)
if err != nil {
if IsErrKeyNotExist(err) {
return nil
}
return fmt.Errorf("GetPublicKeyByID: %v", err)
}
// Check if user has access to delete this key.
if !doer.IsAdmin && doer.ID != key.OwnerID {
return ErrKeyAccessDenied{doer.ID, key.ID, "public"}
}
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if err = deletePublicKeys(sess, id); err != nil {
return err
}
if err = sess.Commit(); err != nil {
return err
}
return RewriteAuthorizedKeys()
}
// RewriteAuthorizedKeys removes any authorized key and rewrite all keys from database again.
// Note: x.Iterate does not get latest data after insert/delete, so we have to call this function
// outside any session scope independently.
//
// Deprecated: Use PublicKeys.RewriteAuthorizedKeys instead.
func RewriteAuthorizedKeys() error {
sshOpLocker.Lock()
defer sshOpLocker.Unlock()
log.Trace("Doing: RewriteAuthorizedKeys")
_ = os.MkdirAll(conf.SSH.RootPath, os.ModePerm)
fpath := authorizedKeysPath()
tmpPath := fpath + ".tmp"
f, err := os.OpenFile(tmpPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
defer os.Remove(tmpPath)
err = x.Iterate(new(PublicKey), func(idx int, bean any) (err error) {
_, err = f.WriteString((bean.(*PublicKey)).AuthorizedString())
return err
})
_ = f.Close()
if err != nil {
return err
}
if com.IsExist(fpath) {
if err = os.Remove(fpath); err != nil {
return err
}
}
if err = os.Rename(tmpPath, fpath); err != nil {
return err
}
return nil
}
// ________ .__ ____ __.
// \______ \ ____ ______ | | ____ ___.__.| |/ _|____ ___.__.
// | | \_/ __ \\____ \| | / _ < | || <_/ __ < | |
// | ` \ ___/| |_> > |_( <_> )___ || | \ ___/\___ |
// /_______ /\___ > __/|____/\____// ____||____|__ \___ > ____|
// \/ \/|__| \/ \/ \/\/
// DeployKey represents deploy key information and its relation with repository.
type DeployKey struct {
ID int64
KeyID int64 `xorm:"UNIQUE(s) INDEX"`
RepoID int64 `xorm:"UNIQUE(s) INDEX"`
Name string
Fingerprint string
Content string `xorm:"-" json:"-" gorm:"-"`
Created time.Time `xorm:"-" json:"-" gorm:"-"`
CreatedUnix int64
Updated time.Time `xorm:"-" json:"-" gorm:"-"` // Note: Updated must below Created for AfterSet.
UpdatedUnix int64
HasRecentActivity bool `xorm:"-" json:"-" gorm:"-"`
HasUsed bool `xorm:"-" json:"-" gorm:"-"`
}
func (k *DeployKey) BeforeInsert() {
k.CreatedUnix = time.Now().Unix()
}
func (k *DeployKey) BeforeUpdate() {
k.UpdatedUnix = time.Now().Unix()
}
func (k *DeployKey) AfterSet(colName string, _ xorm.Cell) {
switch colName {
case "created_unix":
k.Created = time.Unix(k.CreatedUnix, 0).Local()
case "updated_unix":
k.Updated = time.Unix(k.UpdatedUnix, 0).Local()
k.HasUsed = k.Updated.After(k.Created)
k.HasRecentActivity = k.Updated.Add(7 * 24 * time.Hour).After(time.Now())
}
}
// GetContent gets associated public key content.
func (k *DeployKey) GetContent() error {
pkey, err := GetPublicKeyByID(k.KeyID)
if err != nil {
return err
}
k.Content = pkey.Content
return nil
}
func checkDeployKey(e Engine, keyID, repoID int64, name string) error {
// Note: We want error detail, not just true or false here.
has, err := e.Where("key_id = ? AND repo_id = ?", keyID, repoID).Get(new(DeployKey))
if err != nil {
return err
} else if has {
return ErrDeployKeyAlreadyExist{keyID, repoID}
}
has, err = e.Where("repo_id = ? AND name = ?", repoID, name).Get(new(DeployKey))
if err != nil {
return err
} else if has {
return ErrDeployKeyNameAlreadyUsed{repoID, name}
}
return nil
}
// addDeployKey adds new key-repo relation.
func addDeployKey(e *xorm.Session, keyID, repoID int64, name, fingerprint string) (*DeployKey, error) {
if err := checkDeployKey(e, keyID, repoID, name); err != nil {
return nil, err
}
key := &DeployKey{
KeyID: keyID,
RepoID: repoID,
Name: name,
Fingerprint: fingerprint,
}
_, err := e.Insert(key)
return key, err
}
// HasDeployKey returns true if public key is a deploy key of given repository.
func HasDeployKey(keyID, repoID int64) bool {
has, _ := x.Where("key_id = ? AND repo_id = ?", keyID, repoID).Get(new(DeployKey))
return has
}
// AddDeployKey add new deploy key to database and authorized_keys file.
func AddDeployKey(repoID int64, name, content string) (*DeployKey, error) {
if err := checkKeyContent(content); err != nil {
return nil, err
}
pkey := &PublicKey{
Content: content,
Mode: AccessModeRead,
Type: KeyTypeDeploy,
}
has, err := x.Get(pkey)
if err != nil {
return nil, err
}
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return nil, err
}
// First time use this deploy key.
if !has {
if err = addKey(sess, pkey); err != nil {
return nil, fmt.Errorf("addKey: %v", err)
}
}
key, err := addDeployKey(sess, pkey.ID, repoID, name, pkey.Fingerprint)
if err != nil {
return nil, fmt.Errorf("addDeployKey: %v", err)
}
return key, sess.Commit()
}
var _ errutil.NotFound = (*ErrDeployKeyNotExist)(nil)
type ErrDeployKeyNotExist struct {
args map[string]any
}
func IsErrDeployKeyNotExist(err error) bool {
_, ok := err.(ErrDeployKeyNotExist)
return ok
}
func (err ErrDeployKeyNotExist) Error() string {
return fmt.Sprintf("deploy key does not exist: %v", err.args)
}
func (ErrDeployKeyNotExist) NotFound() bool {
return true
}
// GetDeployKeyByID returns deploy key by given ID.
func GetDeployKeyByID(id int64) (*DeployKey, error) {
key := new(DeployKey)
has, err := x.Id(id).Get(key)
if err != nil {
return nil, err
} else if !has {
return nil, ErrDeployKeyNotExist{args: map[string]any{"deployKeyID": id}}
}
return key, nil
}
// GetDeployKeyByRepo returns deploy key by given public key ID and repository ID.
func GetDeployKeyByRepo(keyID, repoID int64) (*DeployKey, error) {
key := &DeployKey{
KeyID: keyID,
RepoID: repoID,
}
has, err := x.Get(key)
if err != nil {
return nil, err
} else if !has {
return nil, ErrDeployKeyNotExist{args: map[string]any{"keyID": keyID, "repoID": repoID}}
}
return key, nil
}
// UpdateDeployKey updates deploy key information.
func UpdateDeployKey(key *DeployKey) error {
_, err := x.Id(key.ID).AllCols().Update(key)
return err
}
// DeleteDeployKey deletes deploy key from its repository authorized_keys file if needed.
func DeleteDeployKey(doer *User, id int64) error {
key, err := GetDeployKeyByID(id)
if err != nil {
if IsErrDeployKeyNotExist(err) {
return nil
}
return fmt.Errorf("GetDeployKeyByID: %v", err)
}
// Check if user has access to delete this key.
if !doer.IsAdmin {
repo, err := GetRepositoryByID(key.RepoID)
if err != nil {
return fmt.Errorf("GetRepositoryByID: %v", err)
}
if !Handle.Permissions().Authorize(context.TODO(), doer.ID, repo.ID, AccessModeAdmin,
AccessModeOptions{
OwnerID: repo.OwnerID,
Private: repo.IsPrivate,
},
) {
return ErrKeyAccessDenied{doer.ID, key.ID, "deploy"}
}
}
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if _, err = sess.ID(key.ID).Delete(new(DeployKey)); err != nil {
return fmt.Errorf("delete deploy key [%d]: %v", key.ID, err)
}
// Check if this is the last reference to same key content.
has, err := sess.Where("key_id = ?", key.KeyID).Get(new(DeployKey))
if err != nil {
return err
} else if !has {
if err = deletePublicKeys(sess, key.KeyID); err != nil {
return err
}
}
return sess.Commit()
}
// ListDeployKeys returns all deploy keys by given repository ID.
func ListDeployKeys(repoID int64) ([]*DeployKey, error) {
keys := make([]*DeployKey, 0, 5)
return keys, x.Where("repo_id = ?", repoID).Find(&keys)
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/repo_collaboration.go | internal/database/repo_collaboration.go | // Copyright 2016 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"fmt"
log "unknwon.dev/clog/v2"
api "github.com/gogs/go-gogs-client"
)
// Collaboration represent the relation between an individual and a repository.
type Collaboration struct {
ID int64 `gorm:"primary_key"`
UserID int64 `xorm:"UNIQUE(s) INDEX NOT NULL" gorm:"uniqueIndex:collaboration_user_repo_unique;index;not null"`
RepoID int64 `xorm:"UNIQUE(s) INDEX NOT NULL" gorm:"uniqueIndex:collaboration_user_repo_unique;index;not null"`
Mode AccessMode `xorm:"DEFAULT 2 NOT NULL" gorm:"not null;default:2"`
}
func (c *Collaboration) ModeI18nKey() string {
switch c.Mode {
case AccessModeRead:
return "repo.settings.collaboration.read"
case AccessModeWrite:
return "repo.settings.collaboration.write"
case AccessModeAdmin:
return "repo.settings.collaboration.admin"
default:
return "repo.settings.collaboration.undefined"
}
}
// IsCollaborator returns true if the user is a collaborator of the repository.
func IsCollaborator(repoID, userID int64) bool {
collaboration := &Collaboration{
RepoID: repoID,
UserID: userID,
}
has, err := x.Get(collaboration)
if err != nil {
log.Error("get collaboration [repo_id: %d, user_id: %d]: %v", repoID, userID, err)
return false
}
return has
}
func (r *Repository) IsCollaborator(userID int64) bool {
return IsCollaborator(r.ID, userID)
}
// AddCollaborator adds new collaboration to a repository with default access mode.
func (r *Repository) AddCollaborator(u *User) error {
collaboration := &Collaboration{
RepoID: r.ID,
UserID: u.ID,
}
has, err := x.Get(collaboration)
if err != nil {
return err
} else if has {
return nil
}
collaboration.Mode = AccessModeWrite
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if _, err = sess.Insert(collaboration); err != nil {
return err
} else if err = r.recalculateAccesses(sess); err != nil {
return fmt.Errorf("recalculateAccesses [repo_id: %v]: %v", r.ID, err)
}
return sess.Commit()
}
func (r *Repository) getCollaborations(e Engine) ([]*Collaboration, error) {
collaborations := make([]*Collaboration, 0)
return collaborations, e.Find(&collaborations, &Collaboration{RepoID: r.ID})
}
// Collaborator represents a user with collaboration details.
type Collaborator struct {
*User
Collaboration *Collaboration
}
func (c *Collaborator) APIFormat() *api.Collaborator {
return &api.Collaborator{
User: c.User.APIFormat(),
Permissions: api.Permission{
Admin: c.Collaboration.Mode >= AccessModeAdmin,
Push: c.Collaboration.Mode >= AccessModeWrite,
Pull: c.Collaboration.Mode >= AccessModeRead,
},
}
}
func (r *Repository) getCollaborators(e Engine) ([]*Collaborator, error) {
collaborations, err := r.getCollaborations(e)
if err != nil {
return nil, fmt.Errorf("getCollaborations: %v", err)
}
collaborators := make([]*Collaborator, len(collaborations))
for i, c := range collaborations {
user, err := getUserByID(e, c.UserID)
if err != nil {
return nil, err
}
collaborators[i] = &Collaborator{
User: user,
Collaboration: c,
}
}
return collaborators, nil
}
// GetCollaborators returns the collaborators for a repository
func (r *Repository) GetCollaborators() ([]*Collaborator, error) {
return r.getCollaborators(x)
}
// ChangeCollaborationAccessMode sets new access mode for the collaboration.
func (r *Repository) ChangeCollaborationAccessMode(userID int64, mode AccessMode) error {
// Discard invalid input
if mode <= AccessModeNone || mode > AccessModeOwner {
return nil
}
collaboration := &Collaboration{
RepoID: r.ID,
UserID: userID,
}
has, err := x.Get(collaboration)
if err != nil {
return fmt.Errorf("get collaboration: %v", err)
} else if !has {
return nil
}
if collaboration.Mode == mode {
return nil
}
collaboration.Mode = mode
// If it's an organizational repository, merge with team access level for highest permission
if r.Owner.IsOrganization() {
teams, err := GetUserTeams(r.OwnerID, userID)
if err != nil {
return fmt.Errorf("GetUserTeams: [org_id: %d, user_id: %d]: %v", r.OwnerID, userID, err)
}
for i := range teams {
if mode < teams[i].Authorize {
mode = teams[i].Authorize
}
}
}
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if _, err = sess.ID(collaboration.ID).AllCols().Update(collaboration); err != nil {
return fmt.Errorf("update collaboration: %v", err)
}
access := &Access{
UserID: userID,
RepoID: r.ID,
}
has, err = sess.Get(access)
if err != nil {
return fmt.Errorf("get access record: %v", err)
}
if has {
_, err = sess.Exec("UPDATE access SET mode = ? WHERE user_id = ? AND repo_id = ?", mode, userID, r.ID)
} else {
access.Mode = mode
_, err = sess.Insert(access)
}
if err != nil {
return fmt.Errorf("update/insert access table: %v", err)
}
return sess.Commit()
}
// DeleteCollaboration removes collaboration relation between the user and repository.
func DeleteCollaboration(repo *Repository, userID int64) (err error) {
if !IsCollaborator(repo.ID, userID) {
return nil
}
collaboration := &Collaboration{
RepoID: repo.ID,
UserID: userID,
}
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if has, err := sess.Delete(collaboration); err != nil || has == 0 {
return err
} else if err = repo.recalculateAccesses(sess); err != nil {
return err
}
return sess.Commit()
}
func (r *Repository) DeleteCollaboration(userID int64) error {
return DeleteCollaboration(r, userID)
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/permissions_test.go | internal/database/permissions_test.go | // Copyright 2020 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestPerms(t *testing.T) {
if testing.Short() {
t.Skip()
}
t.Parallel()
ctx := context.Background()
s := &PermissionsStore{
db: newTestDB(t, "PermissionsStore"),
}
for _, tc := range []struct {
name string
test func(t *testing.T, ctx context.Context, s *PermissionsStore)
}{
{"AccessMode", permsAccessMode},
{"Authorize", permsAuthorize},
{"SetRepoPerms", permsSetRepoPerms},
} {
t.Run(tc.name, func(t *testing.T) {
t.Cleanup(func() {
err := clearTables(t, s.db)
require.NoError(t, err)
})
tc.test(t, ctx, s)
})
if t.Failed() {
break
}
}
}
func permsAccessMode(t *testing.T, ctx context.Context, s *PermissionsStore) {
// Set up permissions
err := s.SetRepoPerms(ctx, 1,
map[int64]AccessMode{
2: AccessModeWrite,
3: AccessModeAdmin,
},
)
require.NoError(t, err)
err = s.SetRepoPerms(ctx, 2,
map[int64]AccessMode{
1: AccessModeRead,
},
)
require.NoError(t, err)
publicRepoID := int64(1)
publicRepoOpts := AccessModeOptions{
OwnerID: 98,
}
privateRepoID := int64(2)
privateRepoOpts := AccessModeOptions{
OwnerID: 99,
Private: true,
}
tests := []struct {
name string
userID int64
repoID int64
opts AccessModeOptions
wantAccessMode AccessMode
}{
{
name: "nil repository",
wantAccessMode: AccessModeNone,
},
{
name: "anonymous user has read access to public repository",
repoID: publicRepoID,
opts: publicRepoOpts,
wantAccessMode: AccessModeRead,
},
{
name: "anonymous user has no access to private repository",
repoID: privateRepoID,
opts: privateRepoOpts,
wantAccessMode: AccessModeNone,
},
{
name: "user is the owner",
userID: 98,
repoID: publicRepoID,
opts: publicRepoOpts,
wantAccessMode: AccessModeOwner,
},
{
name: "user 1 has read access to public repo",
userID: 1,
repoID: publicRepoID,
opts: publicRepoOpts,
wantAccessMode: AccessModeRead,
},
{
name: "user 2 has write access to public repo",
userID: 2,
repoID: publicRepoID,
opts: publicRepoOpts,
wantAccessMode: AccessModeWrite,
},
{
name: "user 3 has admin access to public repo",
userID: 3,
repoID: publicRepoID,
opts: publicRepoOpts,
wantAccessMode: AccessModeAdmin,
},
{
name: "user 1 has read access to private repo",
userID: 1,
repoID: privateRepoID,
opts: privateRepoOpts,
wantAccessMode: AccessModeRead,
},
{
name: "user 2 has no access to private repo",
userID: 2,
repoID: privateRepoID,
opts: privateRepoOpts,
wantAccessMode: AccessModeNone,
},
{
name: "user 3 has no access to private repo",
userID: 3,
repoID: privateRepoID,
opts: privateRepoOpts,
wantAccessMode: AccessModeNone,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
mode := s.AccessMode(ctx, test.userID, test.repoID, test.opts)
assert.Equal(t, test.wantAccessMode, mode)
})
}
}
func permsAuthorize(t *testing.T, ctx context.Context, s *PermissionsStore) {
// Set up permissions
err := s.SetRepoPerms(ctx, 1,
map[int64]AccessMode{
1: AccessModeRead,
2: AccessModeWrite,
3: AccessModeAdmin,
},
)
require.NoError(t, err)
repo := &Repository{
ID: 1,
OwnerID: 98,
}
tests := []struct {
name string
userID int64
desired AccessMode
wantAuthorized bool
}{
{
name: "user 1 has read and wants read",
userID: 1,
desired: AccessModeRead,
wantAuthorized: true,
},
{
name: "user 1 has read and wants write",
userID: 1,
desired: AccessModeWrite,
wantAuthorized: false,
},
{
name: "user 2 has write and wants read",
userID: 2,
desired: AccessModeRead,
wantAuthorized: true,
},
{
name: "user 2 has write and wants write",
userID: 2,
desired: AccessModeWrite,
wantAuthorized: true,
},
{
name: "user 2 has write and wants admin",
userID: 2,
desired: AccessModeAdmin,
wantAuthorized: false,
},
{
name: "user 3 has admin and wants read",
userID: 3,
desired: AccessModeRead,
wantAuthorized: true,
},
{
name: "user 3 has admin and wants write",
userID: 3,
desired: AccessModeWrite,
wantAuthorized: true,
},
{
name: "user 3 has admin and wants admin",
userID: 3,
desired: AccessModeAdmin,
wantAuthorized: true,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
authorized := s.Authorize(ctx, test.userID, repo.ID, test.desired,
AccessModeOptions{
OwnerID: repo.OwnerID,
Private: repo.IsPrivate,
},
)
assert.Equal(t, test.wantAuthorized, authorized)
})
}
}
func permsSetRepoPerms(t *testing.T, ctx context.Context, s *PermissionsStore) {
for _, update := range []struct {
repoID int64
accessMap map[int64]AccessMode
}{
{
repoID: 1,
accessMap: map[int64]AccessMode{
1: AccessModeWrite,
2: AccessModeWrite,
3: AccessModeAdmin,
4: AccessModeWrite,
},
},
{
repoID: 2,
accessMap: map[int64]AccessMode{
1: AccessModeWrite,
2: AccessModeRead,
4: AccessModeWrite,
5: AccessModeWrite,
},
},
{
repoID: 1,
accessMap: map[int64]AccessMode{
2: AccessModeWrite,
3: AccessModeAdmin,
},
},
{
repoID: 2,
accessMap: map[int64]AccessMode{
1: AccessModeWrite,
2: AccessModeRead,
5: AccessModeWrite,
},
},
} {
err := s.SetRepoPerms(ctx, update.repoID, update.accessMap)
if err != nil {
t.Fatal(err)
}
}
var accesses []*Access
err := s.db.Order("user_id, repo_id").Find(&accesses).Error
require.NoError(t, err)
// Ignore ID fields
for _, a := range accesses {
a.ID = 0
}
wantAccesses := []*Access{
{UserID: 1, RepoID: 2, Mode: AccessModeWrite},
{UserID: 2, RepoID: 1, Mode: AccessModeWrite},
{UserID: 2, RepoID: 2, Mode: AccessModeRead},
{UserID: 3, RepoID: 1, Mode: AccessModeAdmin},
{UserID: 5, RepoID: 2, Mode: AccessModeWrite},
}
assert.Equal(t, wantAccesses, accesses)
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/login_source_files.go | internal/database/login_source_files.go | // Copyright 2020 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/pkg/errors"
"gopkg.in/ini.v1"
"gogs.io/gogs/internal/auth"
"gogs.io/gogs/internal/auth/github"
"gogs.io/gogs/internal/auth/ldap"
"gogs.io/gogs/internal/auth/pam"
"gogs.io/gogs/internal/auth/smtp"
"gogs.io/gogs/internal/errutil"
"gogs.io/gogs/internal/osutil"
)
// loginSourceFilesStore is the in-memory interface for login source files stored on file system.
type loginSourceFilesStore interface {
// GetByID returns a clone of login source by given ID.
GetByID(id int64) (*LoginSource, error)
// Len returns number of login sources.
Len() int
// List returns a list of login sources filtered by options.
List(opts ListLoginSourceOptions) []*LoginSource
// Update updates in-memory copy of the authentication source.
Update(source *LoginSource)
}
var _ loginSourceFilesStore = (*loginSourceFiles)(nil)
// loginSourceFiles contains authentication sources configured and loaded from local files.
type loginSourceFiles struct {
sync.RWMutex
sources []*LoginSource
clock func() time.Time
}
var _ errutil.NotFound = (*ErrLoginSourceNotExist)(nil)
type ErrLoginSourceNotExist struct {
args errutil.Args
}
func IsErrLoginSourceNotExist(err error) bool {
return errors.As(err, &ErrLoginSourceNotExist{})
}
func (err ErrLoginSourceNotExist) Error() string {
return fmt.Sprintf("login source does not exist: %v", err.args)
}
func (ErrLoginSourceNotExist) NotFound() bool {
return true
}
func (s *loginSourceFiles) GetByID(id int64) (*LoginSource, error) {
s.RLock()
defer s.RUnlock()
for _, source := range s.sources {
if source.ID == id {
return source, nil
}
}
return nil, ErrLoginSourceNotExist{args: errutil.Args{"id": id}}
}
func (s *loginSourceFiles) Len() int {
s.RLock()
defer s.RUnlock()
return len(s.sources)
}
func (s *loginSourceFiles) List(opts ListLoginSourceOptions) []*LoginSource {
s.RLock()
defer s.RUnlock()
list := make([]*LoginSource, 0, s.Len())
for _, source := range s.sources {
if opts.OnlyActivated && !source.IsActived {
continue
}
list = append(list, source)
}
return list
}
func (s *loginSourceFiles) Update(source *LoginSource) {
s.Lock()
defer s.Unlock()
source.Updated = s.clock()
for _, old := range s.sources {
if old.ID == source.ID {
*old = *source
} else if source.IsDefault {
old.IsDefault = false
}
}
}
// loadLoginSourceFiles loads login sources from file system.
func loadLoginSourceFiles(authdPath string, clock func() time.Time) (loginSourceFilesStore, error) {
if !osutil.IsDir(authdPath) {
return &loginSourceFiles{clock: clock}, nil
}
store := &loginSourceFiles{clock: clock}
return store, filepath.Walk(authdPath, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if path == authdPath || !strings.HasSuffix(path, ".conf") {
return nil
} else if info.IsDir() {
return filepath.SkipDir
}
authSource, err := ini.Load(path)
if err != nil {
return errors.Wrap(err, "load file")
}
authSource.NameMapper = ini.TitleUnderscore
// Set general attributes
s := authSource.Section("")
loginSource := &LoginSource{
ID: s.Key("id").MustInt64(),
Name: s.Key("name").String(),
IsActived: s.Key("is_activated").MustBool(),
IsDefault: s.Key("is_default").MustBool(),
File: &loginSourceFile{
path: path,
file: authSource,
},
}
fi, err := os.Stat(path)
if err != nil {
return errors.Wrap(err, "stat file")
}
loginSource.Updated = fi.ModTime()
// Parse authentication source file
authType := s.Key("type").String()
cfgSection := authSource.Section("config")
switch authType {
case "ldap_bind_dn":
var cfg ldap.Config
err = cfgSection.MapTo(&cfg)
if err != nil {
return errors.Wrap(err, `map "config" section`)
}
loginSource.Type = auth.LDAP
loginSource.Provider = ldap.NewProvider(false, &cfg)
case "ldap_simple_auth":
var cfg ldap.Config
err = cfgSection.MapTo(&cfg)
if err != nil {
return errors.Wrap(err, `map "config" section`)
}
loginSource.Type = auth.DLDAP
loginSource.Provider = ldap.NewProvider(true, &cfg)
case "smtp":
var cfg smtp.Config
err = cfgSection.MapTo(&cfg)
if err != nil {
return errors.Wrap(err, `map "config" section`)
}
loginSource.Type = auth.SMTP
loginSource.Provider = smtp.NewProvider(&cfg)
case "pam":
var cfg pam.Config
err = cfgSection.MapTo(&cfg)
if err != nil {
return errors.Wrap(err, `map "config" section`)
}
loginSource.Type = auth.PAM
loginSource.Provider = pam.NewProvider(&cfg)
case "github":
var cfg github.Config
err = cfgSection.MapTo(&cfg)
if err != nil {
return errors.Wrap(err, `map "config" section`)
}
loginSource.Type = auth.GitHub
loginSource.Provider = github.NewProvider(&cfg)
default:
return fmt.Errorf("unknown type %q", authType)
}
store.sources = append(store.sources, loginSource)
return nil
})
}
// loginSourceFileStore is the persistent interface for a login source file.
type loginSourceFileStore interface {
// SetGeneral sets new value to the given key in the general (default) section.
SetGeneral(name, value string)
// SetConfig sets new values to the "config" section.
SetConfig(cfg any) error
// Save persists values to file system.
Save() error
}
var _ loginSourceFileStore = (*loginSourceFile)(nil)
type loginSourceFile struct {
path string
file *ini.File
}
func (f *loginSourceFile) SetGeneral(name, value string) {
f.file.Section("").Key(name).SetValue(value)
}
func (f *loginSourceFile) SetConfig(cfg any) error {
return f.file.Section("config").ReflectFrom(cfg)
}
func (f *loginSourceFile) Save() error {
return f.file.SaveTo(f.path)
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/main_test.go | internal/database/main_test.go | // Copyright 2020 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"flag"
"fmt"
"os"
"testing"
"gorm.io/gorm"
"gorm.io/gorm/logger"
_ "modernc.org/sqlite"
log "unknwon.dev/clog/v2"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/dbtest"
"gogs.io/gogs/internal/testutil"
)
func TestMain(m *testing.M) {
flag.Parse()
level := logger.Silent
if !testing.Verbose() {
// Remove the primary logger and register a noop logger.
log.Remove(log.DefaultConsoleName)
err := log.New("noop", testutil.InitNoopLogger)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
} else {
level = logger.Info
}
// NOTE: AutoMigrate does not respect logger passed in gorm.Config.
logger.Default = logger.Default.LogMode(level)
switch os.Getenv("GOGS_DATABASE_TYPE") {
case "mysql":
conf.UseMySQL = true
case "postgres":
conf.UsePostgreSQL = true
default:
conf.UseSQLite3 = true
}
os.Exit(m.Run())
}
func newTestDB(t *testing.T, suite string) *gorm.DB {
return dbtest.NewDB(t, suite, append(Tables, legacyTables...)...)
}
func clearTables(t *testing.T, db *gorm.DB) error {
if t.Failed() {
return nil
}
for _, t := range append(Tables, legacyTables...) {
err := db.Where("TRUE").Delete(t).Error
if err != nil {
return err
}
}
return nil
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/database.go | internal/database/database.go | // Copyright 2020 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"fmt"
"path/filepath"
"strings"
"time"
"github.com/pkg/errors"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"gorm.io/gorm/schema"
log "unknwon.dev/clog/v2"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/dbutil"
)
func newLogWriter() (logger.Writer, error) {
sec := conf.File.Section("log.gorm")
w, err := log.NewFileWriter(
filepath.Join(conf.Log.RootPath, "gorm.log"),
log.FileRotationConfig{
Rotate: sec.Key("ROTATE").MustBool(true),
Daily: sec.Key("ROTATE_DAILY").MustBool(true),
MaxSize: sec.Key("MAX_SIZE").MustInt64(100) * 1024 * 1024,
MaxDays: sec.Key("MAX_DAYS").MustInt64(3),
},
)
if err != nil {
return nil, errors.Wrap(err, `create "gorm.log"`)
}
return &dbutil.Logger{Writer: w}, nil
}
// Tables is the list of struct-to-table mappings.
//
// NOTE: Lines are sorted in alphabetical order, each letter in its own line.
//
// ⚠️ WARNING: This list is meant to be read-only.
var Tables = []any{
new(Access), new(AccessToken), new(Action),
new(EmailAddress),
new(Follow),
new(LFSObject), new(LoginSource),
new(Notice),
}
// NewConnection returns a new database connection with the given logger.
func NewConnection(w logger.Writer) (*gorm.DB, error) {
level := logger.Info
if conf.IsProdMode() {
level = logger.Warn
}
// NOTE: AutoMigrate does not respect logger passed in gorm.Config.
logger.Default = logger.New(w, logger.Config{
SlowThreshold: 100 * time.Millisecond,
LogLevel: level,
})
db, err := dbutil.OpenDB(
conf.Database,
&gorm.Config{
SkipDefaultTransaction: true,
NamingStrategy: schema.NamingStrategy{
SingularTable: true,
},
NowFunc: func() time.Time {
return time.Now().UTC().Truncate(time.Microsecond)
},
},
)
if err != nil {
return nil, errors.Wrap(err, "open database")
}
sqlDB, err := db.DB()
if err != nil {
return nil, errors.Wrap(err, "get underlying *sql.DB")
}
sqlDB.SetMaxOpenConns(conf.Database.MaxOpenConns)
sqlDB.SetMaxIdleConns(conf.Database.MaxIdleConns)
sqlDB.SetConnMaxLifetime(time.Minute)
switch conf.Database.Type {
case "postgres":
conf.UsePostgreSQL = true
case "mysql":
conf.UseMySQL = true
db = db.Set("gorm:table_options", "ENGINE=InnoDB").Session(&gorm.Session{})
case "sqlite3":
conf.UseSQLite3 = true
case "mssql":
conf.UseMSSQL = true
default:
panic("unreachable")
}
// NOTE: GORM has problem detecting existing columns, see
// https://github.com/gogs/gogs/issues/6091. Therefore, only use it to create new
// tables, and do customize migration with future changes.
for _, table := range Tables {
if db.Migrator().HasTable(table) {
continue
}
name := strings.TrimPrefix(fmt.Sprintf("%T", table), "*database.")
err = db.Migrator().AutoMigrate(table)
if err != nil {
return nil, errors.Wrapf(err, "auto migrate %q", name)
}
log.Trace("Auto migrated %q", name)
}
loadedLoginSourceFilesStore, err = loadLoginSourceFiles(filepath.Join(conf.CustomDir(), "conf", "auth.d"), db.NowFunc)
if err != nil {
return nil, errors.Wrap(err, "load login source files")
}
// Initialize the database handle.
Handle = &DB{db: db}
return db, nil
}
// DB is the database handler for the storage layer.
type DB struct {
db *gorm.DB
}
// Handle is the global database handle. It could be `nil` during the
// installation mode.
//
// NOTE: Because we need to register all the routes even during the installation
// mode (which initially has no database configuration), we have to use a global
// variable since we can't pass a database handler around before it's available.
//
// NOTE: It is not guarded by a mutex because it is only written once either
// during the service start or during the installation process (which is a
// single-thread process).
var Handle *DB
func (db *DB) AccessTokens() *AccessTokensStore {
return newAccessTokensStore(db.db)
}
func (db *DB) Actions() *ActionsStore {
return newActionsStore(db.db)
}
func (db *DB) LFS() *LFSStore {
return newLFSStore(db.db)
}
// NOTE: It is not guarded by a mutex because it only gets written during the
// service start.
var loadedLoginSourceFilesStore loginSourceFilesStore
func (db *DB) LoginSources() *LoginSourcesStore {
return newLoginSourcesStore(db.db, loadedLoginSourceFilesStore)
}
func (db *DB) Notices() *NoticesStore {
return newNoticesStore(db.db)
}
func (db *DB) Organizations() *OrganizationsStore {
return newOrganizationsStoreStore(db.db)
}
func (db *DB) Permissions() *PermissionsStore {
return newPermissionsStore(db.db)
}
func (db *DB) PublicKey() *PublicKeysStore {
return newPublicKeysStore(db.db)
}
func (db *DB) Repositories() *RepositoriesStore {
return newReposStore(db.db)
}
func (db *DB) TwoFactors() *TwoFactorsStore {
return newTwoFactorsStore(db.db)
}
func (db *DB) Users() *UsersStore {
return newUsersStore(db.db)
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/release.go | internal/database/release.go | // Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"fmt"
"sort"
"strings"
"time"
log "unknwon.dev/clog/v2"
"xorm.io/xorm"
"github.com/gogs/git-module"
api "github.com/gogs/go-gogs-client"
"gogs.io/gogs/internal/errutil"
"gogs.io/gogs/internal/process"
)
// Release represents a release of repository.
type Release struct {
ID int64
RepoID int64
Repo *Repository `xorm:"-" json:"-" gorm:"-"`
PublisherID int64
Publisher *User `xorm:"-" json:"-" gorm:"-"`
TagName string
LowerTagName string
Target string
Title string
Sha1 string `xorm:"VARCHAR(40)"`
NumCommits int64
NumCommitsBehind int64 `xorm:"-" json:"-" gorm:"-"`
Note string `xorm:"TEXT"`
IsDraft bool `xorm:"NOT NULL DEFAULT false"`
IsPrerelease bool
Created time.Time `xorm:"-" json:"-" gorm:"-"`
CreatedUnix int64
Attachments []*Attachment `xorm:"-" json:"-" gorm:"-"`
}
func (r *Release) BeforeInsert() {
if r.CreatedUnix == 0 {
r.CreatedUnix = time.Now().Unix()
}
}
func (r *Release) AfterSet(colName string, _ xorm.Cell) {
switch colName {
case "created_unix":
r.Created = time.Unix(r.CreatedUnix, 0).Local()
}
}
func (r *Release) loadAttributes(e Engine) (err error) {
if r.Repo == nil {
r.Repo, err = getRepositoryByID(e, r.RepoID)
if err != nil {
return fmt.Errorf("getRepositoryByID [repo_id: %d]: %v", r.RepoID, err)
}
}
if r.Publisher == nil {
r.Publisher, err = getUserByID(e, r.PublisherID)
if err != nil {
if IsErrUserNotExist(err) {
r.PublisherID = -1
r.Publisher = NewGhostUser()
} else {
return fmt.Errorf("getUserByID.(Publisher) [publisher_id: %d]: %v", r.PublisherID, err)
}
}
}
if r.Attachments == nil {
r.Attachments, err = getAttachmentsByReleaseID(e, r.ID)
if err != nil {
return fmt.Errorf("getAttachmentsByReleaseID [%d]: %v", r.ID, err)
}
}
return nil
}
func (r *Release) LoadAttributes() error {
return r.loadAttributes(x)
}
// This method assumes some fields assigned with values:
// Required - Publisher
func (r *Release) APIFormat() *api.Release {
return &api.Release{
ID: r.ID,
TagName: r.TagName,
TargetCommitish: r.Target,
Name: r.Title,
Body: r.Note,
Draft: r.IsDraft,
Prerelease: r.IsPrerelease,
Author: r.Publisher.APIFormat(),
Created: r.Created,
}
}
// IsReleaseExist returns true if release with given tag name already exists.
func IsReleaseExist(repoID int64, tagName string) (bool, error) {
if tagName == "" {
return false, nil
}
return x.Get(&Release{RepoID: repoID, LowerTagName: strings.ToLower(tagName)})
}
func createTag(gitRepo *git.Repository, r *Release) error {
// Only actual create when publish.
if !r.IsDraft {
if !gitRepo.HasTag(r.TagName) {
commit, err := gitRepo.BranchCommit(r.Target)
if err != nil {
return fmt.Errorf("get branch commit: %v", err)
}
// 🚨 SECURITY: Trim any leading '-' to prevent command line argument injection.
r.TagName = strings.TrimLeft(r.TagName, "-")
if err = gitRepo.CreateTag(r.TagName, commit.ID.String()); err != nil {
if strings.Contains(err.Error(), "is not a valid tag name") {
return ErrInvalidTagName{r.TagName}
}
return err
}
} else {
commit, err := gitRepo.TagCommit(r.TagName)
if err != nil {
return fmt.Errorf("get tag commit: %v", err)
}
r.Sha1 = commit.ID.String()
r.NumCommits, err = commit.CommitsCount()
if err != nil {
return fmt.Errorf("count commits: %v", err)
}
}
}
return nil
}
func (r *Release) preparePublishWebhooks() {
if err := PrepareWebhooks(r.Repo, HookEventTypeRelease, &api.ReleasePayload{
Action: api.HOOK_RELEASE_PUBLISHED,
Release: r.APIFormat(),
Repository: r.Repo.APIFormatLegacy(nil),
Sender: r.Publisher.APIFormat(),
}); err != nil {
log.Error("PrepareWebhooks: %v", err)
}
}
// NewRelease creates a new release with attachments for repository.
func NewRelease(gitRepo *git.Repository, r *Release, uuids []string) error {
isExist, err := IsReleaseExist(r.RepoID, r.TagName)
if err != nil {
return err
} else if isExist {
return ErrReleaseAlreadyExist{r.TagName}
}
if err = createTag(gitRepo, r); err != nil {
return err
}
r.LowerTagName = strings.ToLower(r.TagName)
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if _, err = sess.Insert(r); err != nil {
return fmt.Errorf("insert: %v", err)
}
if len(uuids) > 0 {
if _, err = sess.In("uuid", uuids).Cols("release_id").Update(&Attachment{ReleaseID: r.ID}); err != nil {
return fmt.Errorf("link attachments: %v", err)
}
}
if err = sess.Commit(); err != nil {
return fmt.Errorf("commit: %v", err)
}
// Only send webhook when actually published, skip drafts
if r.IsDraft {
return nil
}
r, err = GetReleaseByID(r.ID)
if err != nil {
return fmt.Errorf("GetReleaseByID: %v", err)
}
r.preparePublishWebhooks()
return nil
}
var _ errutil.NotFound = (*ErrReleaseNotExist)(nil)
type ErrReleaseNotExist struct {
args map[string]any
}
func IsErrReleaseNotExist(err error) bool {
_, ok := err.(ErrReleaseNotExist)
return ok
}
func (err ErrReleaseNotExist) Error() string {
return fmt.Sprintf("release does not exist: %v", err.args)
}
func (ErrReleaseNotExist) NotFound() bool {
return true
}
// GetRelease returns release by given ID.
func GetRelease(repoID int64, tagName string) (*Release, error) {
isExist, err := IsReleaseExist(repoID, tagName)
if err != nil {
return nil, err
} else if !isExist {
return nil, ErrReleaseNotExist{args: map[string]any{"tag": tagName}}
}
r := &Release{RepoID: repoID, LowerTagName: strings.ToLower(tagName)}
if _, err = x.Get(r); err != nil {
return nil, fmt.Errorf("get: %v", err)
}
return r, r.LoadAttributes()
}
// GetReleaseByID returns release with given ID.
func GetReleaseByID(id int64) (*Release, error) {
r := new(Release)
has, err := x.Id(id).Get(r)
if err != nil {
return nil, err
} else if !has {
return nil, ErrReleaseNotExist{args: map[string]any{"releaseID": id}}
}
return r, r.LoadAttributes()
}
// GetPublishedReleasesByRepoID returns a list of published releases of repository.
// If matches is not empty, only published releases in matches will be returned.
// In any case, drafts won't be returned by this function.
func GetPublishedReleasesByRepoID(repoID int64, matches ...string) ([]*Release, error) {
sess := x.Where("repo_id = ?", repoID).And("is_draft = ?", false).Desc("created_unix")
if len(matches) > 0 {
sess.In("tag_name", matches)
}
releases := make([]*Release, 0, 5)
return releases, sess.Find(&releases, new(Release))
}
// GetReleasesByRepoID returns a list of all releases (including drafts) of given repository.
func GetReleasesByRepoID(repoID int64) ([]*Release, error) {
releases := make([]*Release, 0)
return releases, x.Where("repo_id = ?", repoID).Find(&releases)
}
// GetDraftReleasesByRepoID returns all draft releases of repository.
func GetDraftReleasesByRepoID(repoID int64) ([]*Release, error) {
releases := make([]*Release, 0)
return releases, x.Where("repo_id = ?", repoID).And("is_draft = ?", true).Find(&releases)
}
type ReleaseSorter struct {
releases []*Release
}
func (rs *ReleaseSorter) Len() int {
return len(rs.releases)
}
func (rs *ReleaseSorter) Less(i, j int) bool {
diffNum := rs.releases[i].NumCommits - rs.releases[j].NumCommits
if diffNum != 0 {
return diffNum > 0
}
return rs.releases[i].Created.After(rs.releases[j].Created)
}
func (rs *ReleaseSorter) Swap(i, j int) {
rs.releases[i], rs.releases[j] = rs.releases[j], rs.releases[i]
}
// SortReleases sorts releases by number of commits and created time.
func SortReleases(rels []*Release) {
sorter := &ReleaseSorter{releases: rels}
sort.Sort(sorter)
}
// UpdateRelease updates information of a release.
func UpdateRelease(doer *User, gitRepo *git.Repository, r *Release, isPublish bool, uuids []string) (err error) {
if err = createTag(gitRepo, r); err != nil {
return fmt.Errorf("createTag: %v", err)
}
r.PublisherID = doer.ID
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if _, err = sess.ID(r.ID).AllCols().Update(r); err != nil {
return fmt.Errorf("Update: %v", err)
}
// Unlink all current attachments and link back later if still valid
if _, err = sess.Exec("UPDATE attachment SET release_id = 0 WHERE release_id = ?", r.ID); err != nil {
return fmt.Errorf("unlink current attachments: %v", err)
}
if len(uuids) > 0 {
if _, err = sess.In("uuid", uuids).Cols("release_id").Update(&Attachment{ReleaseID: r.ID}); err != nil {
return fmt.Errorf("link attachments: %v", err)
}
}
if err = sess.Commit(); err != nil {
return fmt.Errorf("commit: %v", err)
}
if !isPublish {
return nil
}
r.Publisher = doer
r.preparePublishWebhooks()
return nil
}
// DeleteReleaseOfRepoByID deletes a release and corresponding Git tag by given ID.
func DeleteReleaseOfRepoByID(repoID, id int64) error {
rel, err := GetReleaseByID(id)
if err != nil {
return fmt.Errorf("GetReleaseByID: %v", err)
}
// Mark sure the delete operation against same repository.
if repoID != rel.RepoID {
return nil
}
repo, err := GetRepositoryByID(rel.RepoID)
if err != nil {
return fmt.Errorf("GetRepositoryByID: %v", err)
}
_, stderr, err := process.ExecDir(-1, repo.RepoPath(),
fmt.Sprintf("DeleteReleaseByID (git tag -d): %d", rel.ID),
"git", "tag", "-d", rel.TagName)
if err != nil && !strings.Contains(stderr, "not found") {
return fmt.Errorf("git tag -d: %v - %s", err, stderr)
}
if _, err = x.Id(rel.ID).Delete(new(Release)); err != nil {
return fmt.Errorf("delete: %v", err)
}
return nil
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/issue.go | internal/database/issue.go | // Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"context"
"fmt"
"strings"
"time"
"github.com/unknwon/com"
log "unknwon.dev/clog/v2"
"xorm.io/xorm"
api "github.com/gogs/go-gogs-client"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/database/errors"
"gogs.io/gogs/internal/errutil"
"gogs.io/gogs/internal/markup"
"gogs.io/gogs/internal/tool"
)
var ErrMissingIssueNumber = errors.New("No issue number specified")
// Issue represents an issue or pull request of repository.
type Issue struct {
ID int64 `gorm:"primaryKey"`
RepoID int64 `xorm:"INDEX UNIQUE(repo_index)" gorm:"index;uniqueIndex:issue_repo_index_unique;not null"`
Repo *Repository `xorm:"-" json:"-" gorm:"-"`
Index int64 `xorm:"UNIQUE(repo_index)" gorm:"uniqueIndex:issue_repo_index_unique;not null"` // Index in one repository.
PosterID int64 `gorm:"index"`
Poster *User `xorm:"-" json:"-" gorm:"-"`
Title string `xorm:"name" gorm:"name"`
Content string `xorm:"TEXT" gorm:"type:TEXT"`
RenderedContent string `xorm:"-" json:"-" gorm:"-"`
Labels []*Label `xorm:"-" json:"-" gorm:"-"`
MilestoneID int64 `gorm:"index"`
Milestone *Milestone `xorm:"-" json:"-" gorm:"-"`
Priority int
AssigneeID int64 `gorm:"index"`
Assignee *User `xorm:"-" json:"-" gorm:"-"`
IsClosed bool
IsRead bool `xorm:"-" json:"-" gorm:"-"`
IsPull bool // Indicates whether is a pull request or not.
PullRequest *PullRequest `xorm:"-" json:"-" gorm:"-"`
NumComments int
Deadline time.Time `xorm:"-" json:"-" gorm:"-"`
DeadlineUnix int64
Created time.Time `xorm:"-" json:"-" gorm:"-"`
CreatedUnix int64
Updated time.Time `xorm:"-" json:"-" gorm:"-"`
UpdatedUnix int64
Attachments []*Attachment `xorm:"-" json:"-" gorm:"-"`
Comments []*Comment `xorm:"-" json:"-" gorm:"-"`
}
func (issue *Issue) BeforeInsert() {
issue.CreatedUnix = time.Now().Unix()
issue.UpdatedUnix = issue.CreatedUnix
}
func (issue *Issue) BeforeUpdate() {
issue.UpdatedUnix = time.Now().Unix()
issue.DeadlineUnix = issue.Deadline.Unix()
}
func (issue *Issue) AfterSet(colName string, _ xorm.Cell) {
switch colName {
case "deadline_unix":
issue.Deadline = time.Unix(issue.DeadlineUnix, 0).Local()
case "created_unix":
issue.Created = time.Unix(issue.CreatedUnix, 0).Local()
case "updated_unix":
issue.Updated = time.Unix(issue.UpdatedUnix, 0).Local()
}
}
// Deprecated: Use Users.GetByID instead.
func getUserByID(e Engine, id int64) (*User, error) {
u := new(User)
has, err := e.ID(id).Get(u)
if err != nil {
return nil, err
} else if !has {
return nil, ErrUserNotExist{args: errutil.Args{"userID": id}}
}
// TODO(unknwon): Rely on AfterFind hook to sanitize user full name.
u.FullName = markup.Sanitize(u.FullName)
return u, nil
}
func (issue *Issue) loadAttributes(e Engine) (err error) {
if issue.Repo == nil {
issue.Repo, err = getRepositoryByID(e, issue.RepoID)
if err != nil {
return fmt.Errorf("getRepositoryByID [%d]: %v", issue.RepoID, err)
}
}
if issue.Poster == nil {
issue.Poster, err = getUserByID(e, issue.PosterID)
if err != nil {
if IsErrUserNotExist(err) {
issue.PosterID = -1
issue.Poster = NewGhostUser()
} else {
return fmt.Errorf("getUserByID.(Poster) [%d]: %v", issue.PosterID, err)
}
}
}
if issue.Labels == nil {
issue.Labels, err = getLabelsByIssueID(e, issue.ID)
if err != nil {
return fmt.Errorf("getLabelsByIssueID [%d]: %v", issue.ID, err)
}
}
if issue.Milestone == nil && issue.MilestoneID > 0 {
issue.Milestone, err = getMilestoneByRepoID(e, issue.RepoID, issue.MilestoneID)
if err != nil {
return fmt.Errorf("getMilestoneByRepoID [repo_id: %d, milestone_id: %d]: %v", issue.RepoID, issue.MilestoneID, err)
}
}
if issue.Assignee == nil && issue.AssigneeID > 0 {
issue.Assignee, err = getUserByID(e, issue.AssigneeID)
if err != nil {
return fmt.Errorf("getUserByID.(assignee) [%d]: %v", issue.AssigneeID, err)
}
}
if issue.IsPull && issue.PullRequest == nil {
// It is possible pull request is not yet created.
issue.PullRequest, err = getPullRequestByIssueID(e, issue.ID)
if err != nil && !IsErrPullRequestNotExist(err) {
return fmt.Errorf("getPullRequestByIssueID [%d]: %v", issue.ID, err)
}
}
if issue.Attachments == nil {
issue.Attachments, err = getAttachmentsByIssueID(e, issue.ID)
if err != nil {
return fmt.Errorf("getAttachmentsByIssueID [%d]: %v", issue.ID, err)
}
}
if issue.Comments == nil {
issue.Comments, err = getCommentsByIssueID(e, issue.ID)
if err != nil {
return fmt.Errorf("getCommentsByIssueID [%d]: %v", issue.ID, err)
}
}
return nil
}
func (issue *Issue) LoadAttributes() error {
return issue.loadAttributes(x)
}
func (issue *Issue) HTMLURL() string {
var path string
if issue.IsPull {
path = "pulls"
} else {
path = "issues"
}
return fmt.Sprintf("%s/%s/%d", issue.Repo.HTMLURL(), path, issue.Index)
}
// State returns string representation of issue status.
func (issue *Issue) State() api.StateType {
if issue.IsClosed {
return api.STATE_CLOSED
}
return api.STATE_OPEN
}
// This method assumes some fields assigned with values:
// Required - Poster, Labels,
// Optional - Milestone, Assignee, PullRequest
func (issue *Issue) APIFormat() *api.Issue {
apiLabels := make([]*api.Label, len(issue.Labels))
for i := range issue.Labels {
apiLabels[i] = issue.Labels[i].APIFormat()
}
apiIssue := &api.Issue{
ID: issue.ID,
Index: issue.Index,
Poster: issue.Poster.APIFormat(),
Title: issue.Title,
Body: issue.Content,
Labels: apiLabels,
State: issue.State(),
Comments: issue.NumComments,
Created: issue.Created,
Updated: issue.Updated,
}
if issue.Milestone != nil {
apiIssue.Milestone = issue.Milestone.APIFormat()
}
if issue.Assignee != nil {
apiIssue.Assignee = issue.Assignee.APIFormat()
}
if issue.IsPull {
apiIssue.PullRequest = &api.PullRequestMeta{
HasMerged: issue.PullRequest.HasMerged,
}
if issue.PullRequest.HasMerged {
apiIssue.PullRequest.Merged = &issue.PullRequest.Merged
}
}
return apiIssue
}
// HashTag returns unique hash tag for issue.
func (issue *Issue) HashTag() string {
return "issue-" + com.ToStr(issue.ID)
}
// IsPoster returns true if given user by ID is the poster.
func (issue *Issue) IsPoster(uid int64) bool {
return issue.PosterID == uid
}
func (issue *Issue) hasLabel(e Engine, labelID int64) bool {
return hasIssueLabel(e, issue.ID, labelID)
}
// HasLabel returns true if issue has been labeled by given ID.
func (issue *Issue) HasLabel(labelID int64) bool {
return issue.hasLabel(x, labelID)
}
func (issue *Issue) sendLabelUpdatedWebhook(doer *User) {
var err error
if issue.IsPull {
err = issue.PullRequest.LoadIssue()
if err != nil {
log.Error("LoadIssue: %v", err)
return
}
err = PrepareWebhooks(issue.Repo, HookEventTypePullRequest, &api.PullRequestPayload{
Action: api.HOOK_ISSUE_LABEL_UPDATED,
Index: issue.Index,
PullRequest: issue.PullRequest.APIFormat(),
Repository: issue.Repo.APIFormatLegacy(nil),
Sender: doer.APIFormat(),
})
} else {
err = PrepareWebhooks(issue.Repo, HookEventTypeIssues, &api.IssuesPayload{
Action: api.HOOK_ISSUE_LABEL_UPDATED,
Index: issue.Index,
Issue: issue.APIFormat(),
Repository: issue.Repo.APIFormatLegacy(nil),
Sender: doer.APIFormat(),
})
}
if err != nil {
log.Error("PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
}
}
func (issue *Issue) addLabel(e *xorm.Session, label *Label) error {
return newIssueLabel(e, issue, label)
}
// AddLabel adds a new label to the issue.
func (issue *Issue) AddLabel(doer *User, label *Label) error {
if err := NewIssueLabel(issue, label); err != nil {
return err
}
issue.sendLabelUpdatedWebhook(doer)
return nil
}
func (issue *Issue) addLabels(e *xorm.Session, labels []*Label) error {
return newIssueLabels(e, issue, labels)
}
// AddLabels adds a list of new labels to the issue.
func (issue *Issue) AddLabels(doer *User, labels []*Label) error {
if err := NewIssueLabels(issue, labels); err != nil {
return err
}
issue.sendLabelUpdatedWebhook(doer)
return nil
}
func (issue *Issue) getLabels(e Engine) (err error) {
if len(issue.Labels) > 0 {
return nil
}
issue.Labels, err = getLabelsByIssueID(e, issue.ID)
if err != nil {
return fmt.Errorf("getLabelsByIssueID: %v", err)
}
return nil
}
func (issue *Issue) removeLabel(e *xorm.Session, label *Label) error {
return deleteIssueLabel(e, issue, label)
}
// RemoveLabel removes a label from issue by given ID.
func (issue *Issue) RemoveLabel(doer *User, label *Label) error {
if err := DeleteIssueLabel(issue, label); err != nil {
return err
}
issue.sendLabelUpdatedWebhook(doer)
return nil
}
func (issue *Issue) clearLabels(e *xorm.Session) (err error) {
if err = issue.getLabels(e); err != nil {
return fmt.Errorf("getLabels: %v", err)
}
// NOTE: issue.removeLabel slices issue.Labels, so we need to create another slice to be unaffected.
labels := make([]*Label, len(issue.Labels))
copy(labels, issue.Labels)
for i := range labels {
if err = issue.removeLabel(e, labels[i]); err != nil {
return fmt.Errorf("removeLabel: %v", err)
}
}
return nil
}
func (issue *Issue) ClearLabels(doer *User) (err error) {
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if err = issue.clearLabels(sess); err != nil {
return err
}
if err = sess.Commit(); err != nil {
return fmt.Errorf("commit: %v", err)
}
if issue.IsPull {
err = issue.PullRequest.LoadIssue()
if err != nil {
log.Error("LoadIssue: %v", err)
return err
}
err = PrepareWebhooks(issue.Repo, HookEventTypePullRequest, &api.PullRequestPayload{
Action: api.HOOK_ISSUE_LABEL_CLEARED,
Index: issue.Index,
PullRequest: issue.PullRequest.APIFormat(),
Repository: issue.Repo.APIFormatLegacy(nil),
Sender: doer.APIFormat(),
})
} else {
err = PrepareWebhooks(issue.Repo, HookEventTypeIssues, &api.IssuesPayload{
Action: api.HOOK_ISSUE_LABEL_CLEARED,
Index: issue.Index,
Issue: issue.APIFormat(),
Repository: issue.Repo.APIFormatLegacy(nil),
Sender: doer.APIFormat(),
})
}
if err != nil {
log.Error("PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
}
return nil
}
// ReplaceLabels removes all current labels and add new labels to the issue.
func (issue *Issue) ReplaceLabels(labels []*Label) (err error) {
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if err = issue.clearLabels(sess); err != nil {
return fmt.Errorf("clearLabels: %v", err)
} else if err = issue.addLabels(sess, labels); err != nil {
return fmt.Errorf("addLabels: %v", err)
}
return sess.Commit()
}
func (issue *Issue) GetAssignee() (err error) {
if issue.AssigneeID == 0 || issue.Assignee != nil {
return nil
}
issue.Assignee, err = Handle.Users().GetByID(context.TODO(), issue.AssigneeID)
if IsErrUserNotExist(err) {
return nil
}
return err
}
// ReadBy sets issue to be read by given user.
func (issue *Issue) ReadBy(uid int64) error {
return UpdateIssueUserByRead(uid, issue.ID)
}
func updateIssueCols(e Engine, issue *Issue, cols ...string) error {
cols = append(cols, "updated_unix")
_, err := e.ID(issue.ID).Cols(cols...).Update(issue)
return err
}
// UpdateIssueCols only updates values of specific columns for given issue.
func UpdateIssueCols(issue *Issue, cols ...string) error {
return updateIssueCols(x, issue, cols...)
}
func (issue *Issue) changeStatus(e *xorm.Session, doer *User, repo *Repository, isClosed bool) (err error) {
// Nothing should be performed if current status is same as target status
if issue.IsClosed == isClosed {
return nil
}
issue.IsClosed = isClosed
if err = updateIssueCols(e, issue, "is_closed"); err != nil {
return err
} else if err = updateIssueUsersByStatus(e, issue.ID, isClosed); err != nil {
return err
}
// Update issue count of labels
if err = issue.getLabels(e); err != nil {
return err
}
for idx := range issue.Labels {
if issue.IsClosed {
issue.Labels[idx].NumClosedIssues++
} else {
issue.Labels[idx].NumClosedIssues--
}
if err = updateLabel(e, issue.Labels[idx]); err != nil {
return err
}
}
// Update issue count of milestone
if err = changeMilestoneIssueStats(e, issue); err != nil {
return err
}
// New action comment
if _, err = createStatusComment(e, doer, repo, issue); err != nil {
return err
}
return nil
}
// ChangeStatus changes issue status to open or closed.
func (issue *Issue) ChangeStatus(doer *User, repo *Repository, isClosed bool) (err error) {
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if err = issue.changeStatus(sess, doer, repo, isClosed); err != nil {
return err
}
if err = sess.Commit(); err != nil {
return fmt.Errorf("commit: %v", err)
}
if issue.IsPull {
// Merge pull request calls issue.changeStatus so we need to handle separately.
issue.PullRequest.Issue = issue
apiPullRequest := &api.PullRequestPayload{
Index: issue.Index,
PullRequest: issue.PullRequest.APIFormat(),
Repository: repo.APIFormatLegacy(nil),
Sender: doer.APIFormat(),
}
if isClosed {
apiPullRequest.Action = api.HOOK_ISSUE_CLOSED
} else {
apiPullRequest.Action = api.HOOK_ISSUE_REOPENED
}
err = PrepareWebhooks(repo, HookEventTypePullRequest, apiPullRequest)
} else {
apiIssues := &api.IssuesPayload{
Index: issue.Index,
Issue: issue.APIFormat(),
Repository: repo.APIFormatLegacy(nil),
Sender: doer.APIFormat(),
}
if isClosed {
apiIssues.Action = api.HOOK_ISSUE_CLOSED
} else {
apiIssues.Action = api.HOOK_ISSUE_REOPENED
}
err = PrepareWebhooks(repo, HookEventTypeIssues, apiIssues)
}
if err != nil {
log.Error("PrepareWebhooks [is_pull: %v, is_closed: %v]: %v", issue.IsPull, isClosed, err)
}
return nil
}
func (issue *Issue) ChangeTitle(doer *User, title string) (err error) {
oldTitle := issue.Title
issue.Title = title
if err = UpdateIssueCols(issue, "name"); err != nil {
return fmt.Errorf("UpdateIssueCols: %v", err)
}
if issue.IsPull {
issue.PullRequest.Issue = issue
err = PrepareWebhooks(issue.Repo, HookEventTypePullRequest, &api.PullRequestPayload{
Action: api.HOOK_ISSUE_EDITED,
Index: issue.Index,
PullRequest: issue.PullRequest.APIFormat(),
Changes: &api.ChangesPayload{
Title: &api.ChangesFromPayload{
From: oldTitle,
},
},
Repository: issue.Repo.APIFormatLegacy(nil),
Sender: doer.APIFormat(),
})
} else {
err = PrepareWebhooks(issue.Repo, HookEventTypeIssues, &api.IssuesPayload{
Action: api.HOOK_ISSUE_EDITED,
Index: issue.Index,
Issue: issue.APIFormat(),
Changes: &api.ChangesPayload{
Title: &api.ChangesFromPayload{
From: oldTitle,
},
},
Repository: issue.Repo.APIFormatLegacy(nil),
Sender: doer.APIFormat(),
})
}
if err != nil {
log.Error("PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
}
return nil
}
func (issue *Issue) ChangeContent(doer *User, content string) (err error) {
oldContent := issue.Content
issue.Content = content
if err = UpdateIssueCols(issue, "content"); err != nil {
return fmt.Errorf("UpdateIssueCols: %v", err)
}
if issue.IsPull {
issue.PullRequest.Issue = issue
err = PrepareWebhooks(issue.Repo, HookEventTypePullRequest, &api.PullRequestPayload{
Action: api.HOOK_ISSUE_EDITED,
Index: issue.Index,
PullRequest: issue.PullRequest.APIFormat(),
Changes: &api.ChangesPayload{
Body: &api.ChangesFromPayload{
From: oldContent,
},
},
Repository: issue.Repo.APIFormatLegacy(nil),
Sender: doer.APIFormat(),
})
} else {
err = PrepareWebhooks(issue.Repo, HookEventTypeIssues, &api.IssuesPayload{
Action: api.HOOK_ISSUE_EDITED,
Index: issue.Index,
Issue: issue.APIFormat(),
Changes: &api.ChangesPayload{
Body: &api.ChangesFromPayload{
From: oldContent,
},
},
Repository: issue.Repo.APIFormatLegacy(nil),
Sender: doer.APIFormat(),
})
}
if err != nil {
log.Error("PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
}
return nil
}
func (issue *Issue) ChangeAssignee(doer *User, assigneeID int64) (err error) {
issue.AssigneeID = assigneeID
if err = UpdateIssueUserByAssignee(issue); err != nil {
return fmt.Errorf("UpdateIssueUserByAssignee: %v", err)
}
issue.Assignee, err = Handle.Users().GetByID(context.TODO(), issue.AssigneeID)
if err != nil && !IsErrUserNotExist(err) {
log.Error("Failed to get user by ID: %v", err)
return nil
}
// Error not nil here means user does not exist, which is remove assignee.
isRemoveAssignee := err != nil
if issue.IsPull {
issue.PullRequest.Issue = issue
apiPullRequest := &api.PullRequestPayload{
Index: issue.Index,
PullRequest: issue.PullRequest.APIFormat(),
Repository: issue.Repo.APIFormatLegacy(nil),
Sender: doer.APIFormat(),
}
if isRemoveAssignee {
apiPullRequest.Action = api.HOOK_ISSUE_UNASSIGNED
} else {
apiPullRequest.Action = api.HOOK_ISSUE_ASSIGNED
}
err = PrepareWebhooks(issue.Repo, HookEventTypePullRequest, apiPullRequest)
} else {
apiIssues := &api.IssuesPayload{
Index: issue.Index,
Issue: issue.APIFormat(),
Repository: issue.Repo.APIFormatLegacy(nil),
Sender: doer.APIFormat(),
}
if isRemoveAssignee {
apiIssues.Action = api.HOOK_ISSUE_UNASSIGNED
} else {
apiIssues.Action = api.HOOK_ISSUE_ASSIGNED
}
err = PrepareWebhooks(issue.Repo, HookEventTypeIssues, apiIssues)
}
if err != nil {
log.Error("PrepareWebhooks [is_pull: %v, remove_assignee: %v]: %v", issue.IsPull, isRemoveAssignee, err)
}
return nil
}
type NewIssueOptions struct {
Repo *Repository
Issue *Issue
LableIDs []int64
Attachments []string // In UUID format.
IsPull bool
}
func newIssue(e *xorm.Session, opts NewIssueOptions) (err error) {
opts.Issue.Title = strings.TrimSpace(opts.Issue.Title)
opts.Issue.Index = opts.Repo.NextIssueIndex()
if opts.Issue.MilestoneID > 0 {
milestone, err := getMilestoneByRepoID(e, opts.Issue.RepoID, opts.Issue.MilestoneID)
if err != nil && !IsErrMilestoneNotExist(err) {
return fmt.Errorf("getMilestoneByID: %v", err)
}
// Assume milestone is invalid and drop silently.
opts.Issue.MilestoneID = 0
if milestone != nil {
opts.Issue.MilestoneID = milestone.ID
opts.Issue.Milestone = milestone
if err = changeMilestoneAssign(e, opts.Issue, -1); err != nil {
return err
}
}
}
if opts.Issue.AssigneeID > 0 {
assignee, err := getUserByID(e, opts.Issue.AssigneeID)
if err != nil && !IsErrUserNotExist(err) {
return fmt.Errorf("get user by ID: %v", err)
}
if assignee != nil {
opts.Issue.AssigneeID = assignee.ID
opts.Issue.Assignee = assignee
} else {
// The assignee does not exist, drop it
opts.Issue.AssigneeID = 0
}
}
// Milestone and assignee validation should happen before insert actual object.
if _, err = e.Insert(opts.Issue); err != nil {
return err
}
if opts.IsPull {
_, err = e.Exec("UPDATE `repository` SET num_pulls = num_pulls + 1 WHERE id = ?", opts.Issue.RepoID)
} else {
_, err = e.Exec("UPDATE `repository` SET num_issues = num_issues + 1 WHERE id = ?", opts.Issue.RepoID)
}
if err != nil {
return err
}
if len(opts.LableIDs) > 0 {
// During the session, SQLite3 driver cannot handle retrieve objects after update something.
// So we have to get all needed labels first.
labels := make([]*Label, 0, len(opts.LableIDs))
if err = e.In("id", opts.LableIDs).Find(&labels); err != nil {
return fmt.Errorf("find all labels [label_ids: %v]: %v", opts.LableIDs, err)
}
for _, label := range labels {
// Silently drop invalid labels.
if label.RepoID != opts.Repo.ID {
continue
}
if err = opts.Issue.addLabel(e, label); err != nil {
return fmt.Errorf("addLabel [id: %d]: %v", label.ID, err)
}
}
}
if err = newIssueUsers(e, opts.Repo, opts.Issue); err != nil {
return err
}
if len(opts.Attachments) > 0 {
attachments, err := getAttachmentsByUUIDs(e, opts.Attachments)
if err != nil {
return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", opts.Attachments, err)
}
for i := 0; i < len(attachments); i++ {
attachments[i].IssueID = opts.Issue.ID
if _, err = e.ID(attachments[i].ID).Update(attachments[i]); err != nil {
return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
}
}
}
return opts.Issue.loadAttributes(e)
}
// NewIssue creates new issue with labels and attachments for repository.
func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if err = newIssue(sess, NewIssueOptions{
Repo: repo,
Issue: issue,
LableIDs: labelIDs,
Attachments: uuids,
}); err != nil {
return fmt.Errorf("new issue: %v", err)
}
if err = sess.Commit(); err != nil {
return fmt.Errorf("commit: %v", err)
}
if err = NotifyWatchers(&Action{
ActUserID: issue.Poster.ID,
ActUserName: issue.Poster.Name,
OpType: ActionCreateIssue,
Content: fmt.Sprintf("%d|%s", issue.Index, issue.Title),
RepoID: repo.ID,
RepoUserName: repo.Owner.Name,
RepoName: repo.Name,
IsPrivate: repo.IsPrivate,
}); err != nil {
log.Error("NotifyWatchers: %v", err)
}
if err = issue.MailParticipants(); err != nil {
log.Error("MailParticipants: %v", err)
}
if err = PrepareWebhooks(repo, HookEventTypeIssues, &api.IssuesPayload{
Action: api.HOOK_ISSUE_OPENED,
Index: issue.Index,
Issue: issue.APIFormat(),
Repository: repo.APIFormatLegacy(nil),
Sender: issue.Poster.APIFormat(),
}); err != nil {
log.Error("PrepareWebhooks: %v", err)
}
return nil
}
var _ errutil.NotFound = (*ErrIssueNotExist)(nil)
type ErrIssueNotExist struct {
args map[string]any
}
func IsErrIssueNotExist(err error) bool {
_, ok := err.(ErrIssueNotExist)
return ok
}
func (err ErrIssueNotExist) Error() string {
return fmt.Sprintf("issue does not exist: %v", err.args)
}
func (ErrIssueNotExist) NotFound() bool {
return true
}
// GetIssueByRef returns an Issue specified by a GFM reference, e.g. owner/repo#123.
func GetIssueByRef(ref string) (*Issue, error) {
n := strings.IndexByte(ref, byte('#'))
if n == -1 {
return nil, ErrIssueNotExist{args: map[string]any{"ref": ref}}
}
index := com.StrTo(ref[n+1:]).MustInt64()
if index == 0 {
return nil, ErrIssueNotExist{args: map[string]any{"ref": ref}}
}
repo, err := GetRepositoryByRef(ref[:n])
if err != nil {
return nil, err
}
issue, err := GetIssueByIndex(repo.ID, index)
if err != nil {
return nil, err
}
return issue, issue.LoadAttributes()
}
// GetRawIssueByIndex returns raw issue without loading attributes by index in a repository.
func GetRawIssueByIndex(repoID, index int64) (*Issue, error) {
issue := &Issue{
RepoID: repoID,
Index: index,
}
has, err := x.Get(issue)
if err != nil {
return nil, err
} else if !has {
return nil, ErrIssueNotExist{args: map[string]any{"repoID": repoID, "index": index}}
}
return issue, nil
}
// GetIssueByIndex returns issue by index in a repository.
func GetIssueByIndex(repoID, index int64) (*Issue, error) {
issue, err := GetRawIssueByIndex(repoID, index)
if err != nil {
return nil, err
}
return issue, issue.LoadAttributes()
}
func getRawIssueByID(e Engine, id int64) (*Issue, error) {
issue := new(Issue)
has, err := e.ID(id).Get(issue)
if err != nil {
return nil, err
} else if !has {
return nil, ErrIssueNotExist{args: map[string]any{"issueID": id}}
}
return issue, nil
}
func getIssueByID(e Engine, id int64) (*Issue, error) {
issue, err := getRawIssueByID(e, id)
if err != nil {
return nil, err
}
return issue, issue.loadAttributes(e)
}
// GetIssueByID returns an issue by given ID.
func GetIssueByID(id int64) (*Issue, error) {
return getIssueByID(x, id)
}
type IssuesOptions struct {
UserID int64
AssigneeID int64
RepoID int64
PosterID int64
MilestoneID int64
RepoIDs []int64
Page int
IsClosed bool
IsMention bool
IsPull bool
Labels string
SortType string
}
// buildIssuesQuery returns nil if it foresees there won't be any value returned.
func buildIssuesQuery(opts *IssuesOptions) *xorm.Session {
sess := x.NewSession()
if opts.Page <= 0 {
opts.Page = 1
}
if opts.RepoID > 0 {
sess.Where("issue.repo_id=?", opts.RepoID).And("issue.is_closed=?", opts.IsClosed)
} else if opts.RepoIDs != nil {
// In case repository IDs are provided but actually no repository has issue.
if len(opts.RepoIDs) == 0 {
return nil
}
sess.In("issue.repo_id", opts.RepoIDs).And("issue.is_closed=?", opts.IsClosed)
} else {
sess.Where("issue.is_closed=?", opts.IsClosed)
}
if opts.AssigneeID > 0 {
sess.And("issue.assignee_id=?", opts.AssigneeID)
} else if opts.PosterID > 0 {
sess.And("issue.poster_id=?", opts.PosterID)
}
if opts.MilestoneID > 0 {
sess.And("issue.milestone_id=?", opts.MilestoneID)
}
sess.And("issue.is_pull=?", opts.IsPull)
switch opts.SortType {
case "oldest":
sess.Asc("issue.created_unix")
case "recentupdate":
sess.Desc("issue.updated_unix")
case "leastupdate":
sess.Asc("issue.updated_unix")
case "mostcomment":
sess.Desc("issue.num_comments")
case "leastcomment":
sess.Asc("issue.num_comments")
case "priority":
sess.Desc("issue.priority")
default:
sess.Desc("issue.created_unix")
}
if len(opts.Labels) > 0 && opts.Labels != "0" {
labelIDs := strings.Split(opts.Labels, ",")
if len(labelIDs) > 0 {
sess.Join("INNER", "issue_label", "issue.id = issue_label.issue_id").In("issue_label.label_id", labelIDs)
}
}
if opts.IsMention {
sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").And("issue_user.is_mentioned = ?", true)
if opts.UserID > 0 {
sess.And("issue_user.uid = ?", opts.UserID)
}
}
return sess
}
// IssuesCount returns the number of issues by given conditions.
func IssuesCount(opts *IssuesOptions) (int64, error) {
sess := buildIssuesQuery(opts)
if sess == nil {
return 0, nil
}
return sess.Count(&Issue{})
}
// Issues returns a list of issues by given conditions.
func Issues(opts *IssuesOptions) ([]*Issue, error) {
sess := buildIssuesQuery(opts)
if sess == nil {
return make([]*Issue, 0), nil
}
sess.Limit(conf.UI.IssuePagingNum, (opts.Page-1)*conf.UI.IssuePagingNum)
issues := make([]*Issue, 0, conf.UI.IssuePagingNum)
if err := sess.Find(&issues); err != nil {
return nil, fmt.Errorf("find: %v", err)
}
// FIXME: use IssueList to improve performance.
for i := range issues {
if err := issues[i].LoadAttributes(); err != nil {
return nil, fmt.Errorf("LoadAttributes [%d]: %v", issues[i].ID, err)
}
}
return issues, nil
}
// GetParticipantsByIssueID returns all users who are participated in comments of an issue.
func GetParticipantsByIssueID(issueID int64) ([]*User, error) {
userIDs := make([]int64, 0, 5)
if err := x.Table("comment").Cols("poster_id").
Where("issue_id = ?", issueID).
Distinct("poster_id").
Find(&userIDs); err != nil {
return nil, fmt.Errorf("get poster IDs: %v", err)
}
if len(userIDs) == 0 {
return nil, nil
}
users := make([]*User, 0, len(userIDs))
return users, x.In("id", userIDs).Find(&users)
}
// .___ ____ ___
// | | ______ ________ __ ____ | | \______ ___________
// | |/ ___// ___/ | \_/ __ \| | / ___// __ \_ __ \
// | |\___ \ \___ \| | /\ ___/| | /\___ \\ ___/| | \/
// |___/____ >____ >____/ \___ >______//____ >\___ >__|
// \/ \/ \/ \/ \/
// IssueUser represents an issue-user relation.
type IssueUser struct {
ID int64 `gorm:"primary_key"`
UserID int64 `xorm:"uid INDEX" gorm:"column:uid;index"`
IssueID int64
RepoID int64 `xorm:"INDEX" gorm:"index"`
MilestoneID int64
IsRead bool
IsAssigned bool
IsMentioned bool
IsPoster bool
IsClosed bool
}
func newIssueUsers(e *xorm.Session, repo *Repository, issue *Issue) error {
assignees, err := repo.getAssignees(e)
if err != nil {
return fmt.Errorf("getAssignees: %v", err)
}
// Poster can be anyone, append later if not one of assignees.
isPosterAssignee := false
// Leave a seat for poster itself to append later, but if poster is one of assignee
// and just waste 1 unit is cheaper than re-allocate memory once.
issueUsers := make([]*IssueUser, 0, len(assignees)+1)
for _, assignee := range assignees {
isPoster := assignee.ID == issue.PosterID
issueUsers = append(issueUsers, &IssueUser{
IssueID: issue.ID,
RepoID: repo.ID,
UserID: assignee.ID,
IsPoster: isPoster,
IsAssigned: assignee.ID == issue.AssigneeID,
})
if !isPosterAssignee && isPoster {
isPosterAssignee = true
}
}
if !isPosterAssignee {
issueUsers = append(issueUsers, &IssueUser{
IssueID: issue.ID,
RepoID: repo.ID,
UserID: issue.PosterID,
IsPoster: true,
})
}
if _, err = e.Insert(issueUsers); err != nil {
return err
}
return nil
}
// NewIssueUsers adds new issue-user relations for new issue of repository.
func NewIssueUsers(repo *Repository, issue *Issue) (err error) {
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if err = newIssueUsers(sess, repo, issue); err != nil {
return err
}
return sess.Commit()
}
// PairsContains returns true when pairs list contains given issue.
func PairsContains(ius []*IssueUser, issueID, uid int64) int {
for i := range ius {
if ius[i].IssueID == issueID &&
ius[i].UserID == uid {
return i
}
}
return -1
}
// GetIssueUsers returns issue-user pairs by given repository and user.
func GetIssueUsers(rid, uid int64, isClosed bool) ([]*IssueUser, error) {
ius := make([]*IssueUser, 0, 10)
err := x.Where("is_closed=?", isClosed).Find(&ius, &IssueUser{RepoID: rid, UserID: uid})
return ius, err
}
// GetIssueUserPairsByRepoIds returns issue-user pairs by given repository IDs.
func GetIssueUserPairsByRepoIds(rids []int64, isClosed bool, page int) ([]*IssueUser, error) {
if len(rids) == 0 {
return []*IssueUser{}, nil
}
ius := make([]*IssueUser, 0, 10)
sess := x.Limit(20, (page-1)*20).Where("is_closed=?", isClosed).In("repo_id", rids)
err := sess.Find(&ius)
return ius, err
}
// GetIssueUserPairsByMode returns issue-user pairs by given repository and user.
func GetIssueUserPairsByMode(userID, repoID int64, filterMode FilterMode, isClosed bool, page int) ([]*IssueUser, error) {
ius := make([]*IssueUser, 0, 10)
sess := x.Limit(20, (page-1)*20).Where("uid=?", userID).And("is_closed=?", isClosed)
if repoID > 0 {
sess.And("repo_id=?", repoID)
}
switch filterMode {
case FilterModeAssign:
sess.And("is_assigned=?", true)
case FilterModeCreate:
sess.And("is_poster=?", true)
default:
return ius, nil
}
err := sess.Find(&ius)
return ius, err
}
// updateIssueMentions extracts mentioned people from content and
// updates issue-user relations for them.
func updateIssueMentions(e Engine, issueID int64, mentions []string) error {
if len(mentions) == 0 {
return nil
}
for i := range mentions {
mentions[i] = strings.ToLower(mentions[i])
}
users := make([]*User, 0, len(mentions))
if err := e.In("lower_name", mentions).Asc("lower_name").Find(&users); err != nil {
return fmt.Errorf("find mentioned users: %v", err)
}
ids := make([]int64, 0, len(mentions))
for _, user := range users {
ids = append(ids, user.ID)
if !user.IsOrganization() || user.NumMembers == 0 {
continue
}
memberIDs := make([]int64, 0, user.NumMembers)
orgUsers, err := getOrgUsersByOrgID(e, user.ID, 0)
if err != nil {
return fmt.Errorf("getOrgUsersByOrgID [%d]: %v", user.ID, err)
}
for _, orgUser := range orgUsers {
memberIDs = append(memberIDs, orgUser.ID)
}
ids = append(ids, memberIDs...)
}
if err := updateIssueUsersByMentions(e, issueID, ids); err != nil {
return fmt.Errorf("UpdateIssueUsersByMentions: %v", err)
}
return nil
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | true |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/public_keys_test.go | internal/database/public_keys_test.go | // Copyright 2023 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"context"
"fmt"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gogs.io/gogs/internal/conf"
)
func TestPublicKeys(t *testing.T) {
if testing.Short() {
t.Skip()
}
t.Parallel()
ctx := context.Background()
s := &PublicKeysStore{
db: newTestDB(t, "PublicKeysStore"),
}
for _, tc := range []struct {
name string
test func(t *testing.T, ctx context.Context, s *PublicKeysStore)
}{
{"RewriteAuthorizedKeys", publicKeysRewriteAuthorizedKeys},
} {
t.Run(tc.name, func(t *testing.T) {
t.Cleanup(func() {
err := clearTables(t, s.db)
require.NoError(t, err)
})
tc.test(t, ctx, s)
})
if t.Failed() {
break
}
}
}
func publicKeysRewriteAuthorizedKeys(t *testing.T, ctx context.Context, s *PublicKeysStore) {
// TODO: Use PublicKeys.Add to replace SQL hack when the method is available.
publicKey := &PublicKey{
OwnerID: 1,
Name: "test-key",
Fingerprint: "12:f8:7e:78:61:b4:bf:e2:de:24:15:96:4e:d4:72:53",
Content: "test-key-content",
}
err := s.db.Create(publicKey).Error
require.NoError(t, err)
tempSSHRootPath := filepath.Join(os.TempDir(), "publicKeysRewriteAuthorizedKeys-tempSSHRootPath")
conf.SetMockSSH(t, conf.SSHOpts{RootPath: tempSSHRootPath})
err = s.RewriteAuthorizedKeys()
require.NoError(t, err)
authorizedKeys, err := os.ReadFile(authorizedKeysPath())
require.NoError(t, err)
assert.Contains(t, string(authorizedKeys), fmt.Sprintf("key-%d", publicKey.ID))
assert.Contains(t, string(authorizedKeys), publicKey.Content)
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/login_sources.go | internal/database/login_sources.go | // Copyright 2020 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"context"
"fmt"
"strconv"
"time"
jsoniter "github.com/json-iterator/go"
"github.com/pkg/errors"
"gorm.io/gorm"
"gogs.io/gogs/internal/auth"
"gogs.io/gogs/internal/auth/github"
"gogs.io/gogs/internal/auth/ldap"
"gogs.io/gogs/internal/auth/pam"
"gogs.io/gogs/internal/auth/smtp"
"gogs.io/gogs/internal/errutil"
)
// LoginSource represents an external way for authorizing users.
type LoginSource struct {
ID int64 `gorm:"primaryKey"`
Type auth.Type
Name string `xorm:"UNIQUE" gorm:"unique"`
IsActived bool `xorm:"NOT NULL DEFAULT false" gorm:"not null"`
IsDefault bool `xorm:"DEFAULT false"`
Provider auth.Provider `xorm:"-" gorm:"-"`
Config string `xorm:"TEXT cfg" gorm:"column:cfg;type:TEXT" json:"RawConfig"`
Created time.Time `xorm:"-" gorm:"-" json:"-"`
CreatedUnix int64
Updated time.Time `xorm:"-" gorm:"-" json:"-"`
UpdatedUnix int64
File loginSourceFileStore `xorm:"-" gorm:"-" json:"-"`
}
// BeforeSave implements the GORM save hook.
func (s *LoginSource) BeforeSave(_ *gorm.DB) (err error) {
if s.Provider == nil {
return nil
}
s.Config, err = jsoniter.MarshalToString(s.Provider.Config())
return err
}
// BeforeCreate implements the GORM create hook.
func (s *LoginSource) BeforeCreate(tx *gorm.DB) error {
if s.CreatedUnix == 0 {
s.CreatedUnix = tx.NowFunc().Unix()
s.UpdatedUnix = s.CreatedUnix
}
return nil
}
// BeforeUpdate implements the GORM update hook.
func (s *LoginSource) BeforeUpdate(tx *gorm.DB) error {
s.UpdatedUnix = tx.NowFunc().Unix()
return nil
}
type mockProviderConfig struct {
ExternalAccount *auth.ExternalAccount
}
// AfterFind implements the GORM query hook.
func (s *LoginSource) AfterFind(_ *gorm.DB) error {
s.Created = time.Unix(s.CreatedUnix, 0).Local()
s.Updated = time.Unix(s.UpdatedUnix, 0).Local()
switch s.Type {
case auth.LDAP:
var cfg ldap.Config
err := jsoniter.UnmarshalFromString(s.Config, &cfg)
if err != nil {
return err
}
s.Provider = ldap.NewProvider(false, &cfg)
case auth.DLDAP:
var cfg ldap.Config
err := jsoniter.UnmarshalFromString(s.Config, &cfg)
if err != nil {
return err
}
s.Provider = ldap.NewProvider(true, &cfg)
case auth.SMTP:
var cfg smtp.Config
err := jsoniter.UnmarshalFromString(s.Config, &cfg)
if err != nil {
return err
}
s.Provider = smtp.NewProvider(&cfg)
case auth.PAM:
var cfg pam.Config
err := jsoniter.UnmarshalFromString(s.Config, &cfg)
if err != nil {
return err
}
s.Provider = pam.NewProvider(&cfg)
case auth.GitHub:
var cfg github.Config
err := jsoniter.UnmarshalFromString(s.Config, &cfg)
if err != nil {
return err
}
s.Provider = github.NewProvider(&cfg)
case auth.Mock:
var cfg mockProviderConfig
err := jsoniter.UnmarshalFromString(s.Config, &cfg)
if err != nil {
return err
}
mockProvider := NewMockProvider()
mockProvider.AuthenticateFunc.SetDefaultReturn(cfg.ExternalAccount, nil)
s.Provider = mockProvider
default:
return fmt.Errorf("unrecognized login source type: %v", s.Type)
}
return nil
}
func (s *LoginSource) TypeName() string {
return auth.Name(s.Type)
}
func (s *LoginSource) IsLDAP() bool {
return s.Type == auth.LDAP
}
func (s *LoginSource) IsDLDAP() bool {
return s.Type == auth.DLDAP
}
func (s *LoginSource) IsSMTP() bool {
return s.Type == auth.SMTP
}
func (s *LoginSource) IsPAM() bool {
return s.Type == auth.PAM
}
func (s *LoginSource) IsGitHub() bool {
return s.Type == auth.GitHub
}
func (s *LoginSource) LDAP() *ldap.Config {
return s.Provider.Config().(*ldap.Config)
}
func (s *LoginSource) SMTP() *smtp.Config {
return s.Provider.Config().(*smtp.Config)
}
func (s *LoginSource) PAM() *pam.Config {
return s.Provider.Config().(*pam.Config)
}
func (s *LoginSource) GitHub() *github.Config {
return s.Provider.Config().(*github.Config)
}
// LoginSourcesStore is the storage layer for login sources.
type LoginSourcesStore struct {
db *gorm.DB
files loginSourceFilesStore
}
func newLoginSourcesStore(db *gorm.DB, files loginSourceFilesStore) *LoginSourcesStore {
return &LoginSourcesStore{
db: db,
files: files,
}
}
type CreateLoginSourceOptions struct {
Type auth.Type
Name string
Activated bool
Default bool
Config any
}
type ErrLoginSourceAlreadyExist struct {
args errutil.Args
}
func IsErrLoginSourceAlreadyExist(err error) bool {
return errors.As(err, &ErrLoginSourceAlreadyExist{})
}
func (err ErrLoginSourceAlreadyExist) Error() string {
return fmt.Sprintf("login source already exists: %v", err.args)
}
// Create creates a new login source and persists it to the database. It returns
// ErrLoginSourceAlreadyExist when a login source with same name already exists.
func (s *LoginSourcesStore) Create(ctx context.Context, opts CreateLoginSourceOptions) (*LoginSource, error) {
err := s.db.WithContext(ctx).Where("name = ?", opts.Name).First(new(LoginSource)).Error
if err == nil {
return nil, ErrLoginSourceAlreadyExist{args: errutil.Args{"name": opts.Name}}
} else if !errors.Is(err, gorm.ErrRecordNotFound) {
return nil, err
}
source := &LoginSource{
Type: opts.Type,
Name: opts.Name,
IsActived: opts.Activated,
IsDefault: opts.Default,
}
source.Config, err = jsoniter.MarshalToString(opts.Config)
if err != nil {
return nil, err
}
return source, s.db.WithContext(ctx).Create(source).Error
}
// Count returns the total number of login sources.
func (s *LoginSourcesStore) Count(ctx context.Context) int64 {
var count int64
s.db.WithContext(ctx).Model(new(LoginSource)).Count(&count)
return count + int64(s.files.Len())
}
type ErrLoginSourceInUse struct {
args errutil.Args
}
func IsErrLoginSourceInUse(err error) bool {
return errors.As(err, &ErrLoginSourceInUse{})
}
func (err ErrLoginSourceInUse) Error() string {
return fmt.Sprintf("login source is still used by some users: %v", err.args)
}
// DeleteByID deletes a login source by given ID. It returns ErrLoginSourceInUse
// if at least one user is associated with the login source.
func (s *LoginSourcesStore) DeleteByID(ctx context.Context, id int64) error {
var count int64
err := s.db.WithContext(ctx).Model(new(User)).Where("login_source = ?", id).Count(&count).Error
if err != nil {
return err
} else if count > 0 {
return ErrLoginSourceInUse{args: errutil.Args{"id": id}}
}
return s.db.WithContext(ctx).Where("id = ?", id).Delete(new(LoginSource)).Error
}
// GetByID returns the login source with given ID. It returns
// ErrLoginSourceNotExist when not found.
func (s *LoginSourcesStore) GetByID(ctx context.Context, id int64) (*LoginSource, error) {
source := new(LoginSource)
err := s.db.WithContext(ctx).Where("id = ?", id).First(source).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return s.files.GetByID(id)
}
return nil, err
}
return source, nil
}
type ListLoginSourceOptions struct {
// Whether to only include activated login sources.
OnlyActivated bool
}
// List returns a list of login sources filtered by options.
func (s *LoginSourcesStore) List(ctx context.Context, opts ListLoginSourceOptions) ([]*LoginSource, error) {
var sources []*LoginSource
query := s.db.WithContext(ctx).Order("id ASC")
if opts.OnlyActivated {
query = query.Where("is_actived = ?", true)
}
err := query.Find(&sources).Error
if err != nil {
return nil, err
}
return append(sources, s.files.List(opts)...), nil
}
// ResetNonDefault clears default flag for all the other login sources.
func (s *LoginSourcesStore) ResetNonDefault(ctx context.Context, dflt *LoginSource) error {
err := s.db.WithContext(ctx).
Model(new(LoginSource)).
Where("id != ?", dflt.ID).
Updates(map[string]any{"is_default": false}).
Error
if err != nil {
return err
}
for _, source := range s.files.List(ListLoginSourceOptions{}) {
if source.File != nil && source.ID != dflt.ID {
source.File.SetGeneral("is_default", "false")
if err = source.File.Save(); err != nil {
return errors.Wrap(err, "save file")
}
}
}
s.files.Update(dflt)
return nil
}
// Save persists all values of given login source to database or local file. The
// Updated field is set to current time automatically.
func (s *LoginSourcesStore) Save(ctx context.Context, source *LoginSource) error {
if source.File == nil {
return s.db.WithContext(ctx).Save(source).Error
}
source.File.SetGeneral("name", source.Name)
source.File.SetGeneral("is_activated", strconv.FormatBool(source.IsActived))
source.File.SetGeneral("is_default", strconv.FormatBool(source.IsDefault))
if err := source.File.SetConfig(source.Provider.Config()); err != nil {
return errors.Wrap(err, "set config")
} else if err = source.File.Save(); err != nil {
return errors.Wrap(err, "save file")
}
return nil
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/org_team.go | internal/database/org_team.go | // Copyright 2016 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"context"
"fmt"
"strings"
"xorm.io/xorm"
"gogs.io/gogs/internal/database/errors"
"gogs.io/gogs/internal/errutil"
)
const ownerTeamName = "Owners"
// Team represents a organization team.
type Team struct {
ID int64
OrgID int64 `xorm:"INDEX"`
LowerName string
Name string
Description string
Authorize AccessMode
Repos []*Repository `xorm:"-" json:"-" gorm:"-"`
Members []*User `xorm:"-" json:"-" gorm:"-"`
NumRepos int
NumMembers int
}
func (t *Team) AfterSet(colName string, _ xorm.Cell) {
switch colName {
case "num_repos":
// LEGACY [1.0]: this is backward compatibility bug fix for https://gogs.io/gogs/issues/3671
if t.NumRepos < 0 {
t.NumRepos = 0
}
}
}
// IsOwnerTeam returns true if team is owner team.
func (t *Team) IsOwnerTeam() bool {
return t.Name == ownerTeamName
}
// HasWriteAccess returns true if team has at least write level access mode.
func (t *Team) HasWriteAccess() bool {
return t.Authorize >= AccessModeWrite
}
// IsTeamMember returns true if given user is a member of team.
func (t *Team) IsMember(userID int64) bool {
return IsTeamMember(t.OrgID, t.ID, userID)
}
func (t *Team) getRepositories(e Engine) (err error) {
teamRepos := make([]*TeamRepo, 0, t.NumRepos)
if err = x.Where("team_id=?", t.ID).Find(&teamRepos); err != nil {
return fmt.Errorf("get team-repos: %v", err)
}
t.Repos = make([]*Repository, 0, len(teamRepos))
for i := range teamRepos {
repo, err := getRepositoryByID(e, teamRepos[i].RepoID)
if err != nil {
return fmt.Errorf("getRepositoryById(%d): %v", teamRepos[i].RepoID, err)
}
t.Repos = append(t.Repos, repo)
}
return nil
}
// GetRepositories returns all repositories in team of organization.
func (t *Team) GetRepositories() error {
return t.getRepositories(x)
}
func (t *Team) getMembers(e Engine) (err error) {
t.Members, err = getTeamMembers(e, t.ID)
return err
}
// GetMembers returns all members in team of organization.
func (t *Team) GetMembers() (err error) {
return t.getMembers(x)
}
// AddMember adds new membership of the team to the organization,
// the user will have membership to the organization automatically when needed.
func (t *Team) AddMember(uid int64) error {
return AddTeamMember(t.OrgID, t.ID, uid)
}
// RemoveMember removes member from team of organization.
func (t *Team) RemoveMember(uid int64) error {
return RemoveTeamMember(t.OrgID, t.ID, uid)
}
func (t *Team) hasRepository(e Engine, repoID int64) bool {
return hasTeamRepo(e, t.OrgID, t.ID, repoID)
}
// HasRepository returns true if given repository belong to team.
func (t *Team) HasRepository(repoID int64) bool {
return t.hasRepository(x, repoID)
}
func (t *Team) addRepository(e Engine, repo *Repository) (err error) {
if err = addTeamRepo(e, t.OrgID, t.ID, repo.ID); err != nil {
return err
}
t.NumRepos++
if _, err = e.ID(t.ID).AllCols().Update(t); err != nil {
return fmt.Errorf("update team: %v", err)
}
if err = repo.recalculateTeamAccesses(e, 0); err != nil {
return fmt.Errorf("recalculateAccesses: %v", err)
}
if err = t.getMembers(e); err != nil {
return fmt.Errorf("getMembers: %v", err)
}
for _, u := range t.Members {
if err = watchRepo(e, u.ID, repo.ID, true); err != nil {
return fmt.Errorf("watchRepo: %v", err)
}
}
return nil
}
// AddRepository adds new repository to team of organization.
func (t *Team) AddRepository(repo *Repository) (err error) {
if repo.OwnerID != t.OrgID {
return errors.New("Repository does not belong to organization")
} else if t.HasRepository(repo.ID) {
return nil
}
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if err = t.addRepository(sess, repo); err != nil {
return err
}
return sess.Commit()
}
func (t *Team) removeRepository(e Engine, repo *Repository, recalculate bool) (err error) {
if err = removeTeamRepo(e, t.ID, repo.ID); err != nil {
return err
}
t.NumRepos--
if _, err = e.ID(t.ID).AllCols().Update(t); err != nil {
return err
}
// Don't need to recalculate when delete a repository from organization.
if recalculate {
if err = repo.recalculateTeamAccesses(e, t.ID); err != nil {
return err
}
}
if err = t.getMembers(e); err != nil {
return fmt.Errorf("get team members: %v", err)
}
// TODO: Delete me when this method is migrated to use GORM.
userAccessMode := func(e Engine, userID int64, repo *Repository) (AccessMode, error) {
mode := AccessModeNone
// Everyone has read access to public repository
if !repo.IsPrivate {
mode = AccessModeRead
}
if userID <= 0 {
return mode, nil
}
if userID == repo.OwnerID {
return AccessModeOwner, nil
}
access := &Access{
UserID: userID,
RepoID: repo.ID,
}
if has, err := e.Get(access); !has || err != nil {
return mode, err
}
return access.Mode, nil
}
hasAccess := func(e Engine, userID int64, repo *Repository, testMode AccessMode) (bool, error) {
mode, err := userAccessMode(e, userID, repo)
return mode >= testMode, err
}
for _, member := range t.Members {
has, err := hasAccess(e, member.ID, repo, AccessModeRead)
if err != nil {
return err
} else if has {
continue
}
if err = watchRepo(e, member.ID, repo.ID, false); err != nil {
return err
}
}
return nil
}
// RemoveRepository removes repository from team of organization.
func (t *Team) RemoveRepository(repoID int64) error {
if !t.HasRepository(repoID) {
return nil
}
repo, err := GetRepositoryByID(repoID)
if err != nil {
return err
}
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if err = t.removeRepository(sess, repo, true); err != nil {
return err
}
return sess.Commit()
}
var reservedTeamNames = map[string]struct{}{
"new": {},
}
// IsUsableTeamName return an error if given name is a reserved name or pattern.
func IsUsableTeamName(name string) error {
return isNameAllowed(reservedTeamNames, nil, name)
}
// NewTeam creates a record of new team.
// It's caller's responsibility to assign organization ID.
func NewTeam(t *Team) error {
if t.Name == "" {
return errors.New("empty team name")
} else if t.OrgID == 0 {
return errors.New("OrgID is not assigned")
}
if err := IsUsableTeamName(t.Name); err != nil {
return err
}
has, err := x.Id(t.OrgID).Get(new(User))
if err != nil {
return err
} else if !has {
return ErrOrgNotExist
}
t.LowerName = strings.ToLower(t.Name)
existingTeam := Team{}
has, err = x.Where("org_id=?", t.OrgID).And("lower_name=?", t.LowerName).Get(&existingTeam)
if err != nil {
return err
} else if has {
return ErrTeamAlreadyExist{existingTeam.ID, t.OrgID, t.LowerName}
}
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if _, err = sess.Insert(t); err != nil {
return err
}
// Update organization number of teams.
if _, err = sess.Exec("UPDATE `user` SET num_teams=num_teams+1 WHERE id = ?", t.OrgID); err != nil {
return err
}
return sess.Commit()
}
var _ errutil.NotFound = (*ErrTeamNotExist)(nil)
type ErrTeamNotExist struct {
args map[string]any
}
func IsErrTeamNotExist(err error) bool {
_, ok := err.(ErrTeamNotExist)
return ok
}
func (err ErrTeamNotExist) Error() string {
return fmt.Sprintf("team does not exist: %v", err.args)
}
func (ErrTeamNotExist) NotFound() bool {
return true
}
func getTeamOfOrgByName(e Engine, orgID int64, name string) (*Team, error) {
t := &Team{
OrgID: orgID,
LowerName: strings.ToLower(name),
}
has, err := e.Get(t)
if err != nil {
return nil, err
} else if !has {
return nil, ErrTeamNotExist{args: map[string]any{"orgID": orgID, "name": name}}
}
return t, nil
}
// GetTeamOfOrgByName returns team by given team name and organization.
func GetTeamOfOrgByName(orgID int64, name string) (*Team, error) {
return getTeamOfOrgByName(x, orgID, name)
}
func getTeamByID(e Engine, teamID int64) (*Team, error) {
t := new(Team)
has, err := e.ID(teamID).Get(t)
if err != nil {
return nil, err
} else if !has {
return nil, ErrTeamNotExist{args: map[string]any{"teamID": teamID}}
}
return t, nil
}
// GetTeamByID returns team by given ID.
func GetTeamByID(teamID int64) (*Team, error) {
return getTeamByID(x, teamID)
}
func getTeamsByOrgID(e Engine, orgID int64) ([]*Team, error) {
teams := make([]*Team, 0, 3)
return teams, e.Where("org_id = ?", orgID).Find(&teams)
}
// GetTeamsByOrgID returns all teams belong to given organization.
func GetTeamsByOrgID(orgID int64) ([]*Team, error) {
return getTeamsByOrgID(x, orgID)
}
// UpdateTeam updates information of team.
func UpdateTeam(t *Team, authChanged bool) (err error) {
if t.Name == "" {
return errors.New("empty team name")
}
if len(t.Description) > 255 {
t.Description = t.Description[:255]
}
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
t.LowerName = strings.ToLower(t.Name)
existingTeam := new(Team)
has, err := x.Where("org_id=?", t.OrgID).And("lower_name=?", t.LowerName).And("id!=?", t.ID).Get(existingTeam)
if err != nil {
return err
} else if has {
return ErrTeamAlreadyExist{existingTeam.ID, t.OrgID, t.LowerName}
}
if _, err = sess.ID(t.ID).AllCols().Update(t); err != nil {
return fmt.Errorf("update: %v", err)
}
// Update access for team members if needed.
if authChanged {
if err = t.getRepositories(sess); err != nil {
return fmt.Errorf("getRepositories:%v", err)
}
for _, repo := range t.Repos {
if err = repo.recalculateTeamAccesses(sess, 0); err != nil {
return fmt.Errorf("recalculateTeamAccesses: %v", err)
}
}
}
return sess.Commit()
}
// DeleteTeam deletes given team.
// It's caller's responsibility to assign organization ID.
func DeleteTeam(t *Team) error {
if err := t.GetRepositories(); err != nil {
return err
}
// Get organization.
org, err := Handle.Users().GetByID(context.TODO(), t.OrgID)
if err != nil {
return err
}
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
// Delete all accesses.
for _, repo := range t.Repos {
if err = repo.recalculateTeamAccesses(sess, t.ID); err != nil {
return err
}
}
// Delete team-user.
if _, err = sess.Where("org_id=?", org.ID).Where("team_id=?", t.ID).Delete(new(TeamUser)); err != nil {
return err
}
// Delete team.
if _, err = sess.ID(t.ID).Delete(new(Team)); err != nil {
return err
}
// Update organization number of teams.
if _, err = sess.Exec("UPDATE `user` SET num_teams=num_teams-1 WHERE id=?", t.OrgID); err != nil {
return err
}
return sess.Commit()
}
// ___________ ____ ___
// \__ ___/___ _____ _____ | | \______ ___________
// | |_/ __ \\__ \ / \| | / ___// __ \_ __ \
// | |\ ___/ / __ \| Y Y \ | /\___ \\ ___/| | \/
// |____| \___ >____ /__|_| /______//____ >\___ >__|
// \/ \/ \/ \/ \/
// TeamUser represents an team-user relation.
type TeamUser struct {
ID int64
OrgID int64 `xorm:"INDEX"`
TeamID int64 `xorm:"UNIQUE(s)"`
UID int64 `xorm:"UNIQUE(s)"`
}
func isTeamMember(e Engine, orgID, teamID, uid int64) bool {
has, _ := e.Where("org_id=?", orgID).And("team_id=?", teamID).And("uid=?", uid).Get(new(TeamUser))
return has
}
// IsTeamMember returns true if given user is a member of team.
func IsTeamMember(orgID, teamID, uid int64) bool {
return isTeamMember(x, orgID, teamID, uid)
}
func getTeamMembers(e Engine, teamID int64) (_ []*User, err error) {
teamUsers := make([]*TeamUser, 0, 10)
if err = e.Sql("SELECT `id`, `org_id`, `team_id`, `uid` FROM `team_user` WHERE team_id = ?", teamID).
Find(&teamUsers); err != nil {
return nil, fmt.Errorf("get team-users: %v", err)
}
members := make([]*User, 0, len(teamUsers))
for i := range teamUsers {
member := new(User)
if _, err = e.ID(teamUsers[i].UID).Get(member); err != nil {
return nil, fmt.Errorf("get user '%d': %v", teamUsers[i].UID, err)
}
members = append(members, member)
}
return members, nil
}
// GetTeamMembers returns all members in given team of organization.
func GetTeamMembers(teamID int64) ([]*User, error) {
return getTeamMembers(x, teamID)
}
func getUserTeams(e Engine, orgID, userID int64) ([]*Team, error) {
teamUsers := make([]*TeamUser, 0, 5)
if err := e.Where("uid = ?", userID).And("org_id = ?", orgID).Find(&teamUsers); err != nil {
return nil, err
}
teamIDs := make([]int64, len(teamUsers)+1)
for i := range teamUsers {
teamIDs[i] = teamUsers[i].TeamID
}
teamIDs[len(teamUsers)] = -1
teams := make([]*Team, 0, len(teamIDs))
return teams, e.Where("org_id = ?", orgID).In("id", teamIDs).Find(&teams)
}
// GetUserTeams returns all teams that user belongs to in given organization.
func GetUserTeams(orgID, userID int64) ([]*Team, error) {
return getUserTeams(x, orgID, userID)
}
// AddTeamMember adds new membership of given team to given organization,
// the user will have membership to given organization automatically when needed.
func AddTeamMember(orgID, teamID, userID int64) error {
if IsTeamMember(orgID, teamID, userID) {
return nil
}
if err := AddOrgUser(orgID, userID); err != nil {
return err
}
// Get team and its repositories.
t, err := GetTeamByID(teamID)
if err != nil {
return err
}
t.NumMembers++
if err = t.GetRepositories(); err != nil {
return err
}
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
tu := &TeamUser{
UID: userID,
OrgID: orgID,
TeamID: teamID,
}
if _, err = sess.Insert(tu); err != nil {
return err
} else if _, err = sess.ID(t.ID).Update(t); err != nil {
return err
}
// Give access to team repositories.
for _, repo := range t.Repos {
if err = repo.recalculateTeamAccesses(sess, 0); err != nil {
return err
}
}
// We make sure it exists before.
ou := new(OrgUser)
if _, err = sess.Where("uid = ?", userID).And("org_id = ?", orgID).Get(ou); err != nil {
return err
}
ou.NumTeams++
if t.IsOwnerTeam() {
ou.IsOwner = true
}
if _, err = sess.ID(ou.ID).AllCols().Update(ou); err != nil {
return err
}
return sess.Commit()
}
func removeTeamMember(e Engine, orgID, teamID, uid int64) error {
if !isTeamMember(e, orgID, teamID, uid) {
return nil
}
// Get team and its repositories.
t, err := getTeamByID(e, teamID)
if err != nil {
return err
}
// Check if the user to delete is the last member in owner team.
if t.IsOwnerTeam() && t.NumMembers == 1 {
return ErrLastOrgOwner{UID: uid}
}
t.NumMembers--
if err = t.getRepositories(e); err != nil {
return err
}
// Get organization.
org, err := getUserByID(e, orgID)
if err != nil {
return err
}
tu := &TeamUser{
UID: uid,
OrgID: orgID,
TeamID: teamID,
}
if _, err := e.Delete(tu); err != nil {
return err
} else if _, err = e.ID(t.ID).AllCols().Update(t); err != nil {
return err
}
// Delete access to team repositories.
for _, repo := range t.Repos {
if err = repo.recalculateTeamAccesses(e, 0); err != nil {
return err
}
}
// This must exist.
ou := new(OrgUser)
_, err = e.Where("uid = ?", uid).And("org_id = ?", org.ID).Get(ou)
if err != nil {
return err
}
ou.NumTeams--
if t.IsOwnerTeam() {
ou.IsOwner = false
}
if _, err = e.ID(ou.ID).AllCols().Update(ou); err != nil {
return err
}
return nil
}
// RemoveTeamMember removes member from given team of given organization.
func RemoveTeamMember(orgID, teamID, uid int64) error {
sess := x.NewSession()
defer sess.Close()
if err := sess.Begin(); err != nil {
return err
}
if err := removeTeamMember(sess, orgID, teamID, uid); err != nil {
return err
}
return sess.Commit()
}
// ___________ __________
// \__ ___/___ _____ _____\______ \ ____ ______ ____
// | |_/ __ \\__ \ / \| _// __ \\____ \ / _ \
// | |\ ___/ / __ \| Y Y \ | \ ___/| |_> > <_> )
// |____| \___ >____ /__|_| /____|_ /\___ > __/ \____/
// \/ \/ \/ \/ \/|__|
// TeamRepo represents an team-repository relation.
type TeamRepo struct {
ID int64
OrgID int64 `xorm:"INDEX"`
TeamID int64 `xorm:"UNIQUE(s)"`
RepoID int64 `xorm:"UNIQUE(s)"`
}
func hasTeamRepo(e Engine, orgID, teamID, repoID int64) bool {
has, _ := e.Where("org_id = ?", orgID).And("team_id = ?", teamID).And("repo_id = ?", repoID).Get(new(TeamRepo))
return has
}
// HasTeamRepo returns true if given team has access to the repository of the organization.
func HasTeamRepo(orgID, teamID, repoID int64) bool {
return hasTeamRepo(x, orgID, teamID, repoID)
}
func addTeamRepo(e Engine, orgID, teamID, repoID int64) error {
_, err := e.InsertOne(&TeamRepo{
OrgID: orgID,
TeamID: teamID,
RepoID: repoID,
})
return err
}
// AddTeamRepo adds new repository relation to team.
func AddTeamRepo(orgID, teamID, repoID int64) error {
return addTeamRepo(x, orgID, teamID, repoID)
}
func removeTeamRepo(e Engine, teamID, repoID int64) error {
_, err := e.Delete(&TeamRepo{
TeamID: teamID,
RepoID: repoID,
})
return err
}
// RemoveTeamRepo deletes repository relation to team.
func RemoveTeamRepo(teamID, repoID int64) error {
return removeTeamRepo(x, teamID, repoID)
}
// GetTeamsHaveAccessToRepo returns all teams in an organization that have given access level to the repository.
func GetTeamsHaveAccessToRepo(orgID, repoID int64, mode AccessMode) ([]*Team, error) {
teams := make([]*Team, 0, 5)
return teams, x.Where("team.authorize >= ?", mode).
Join("INNER", "team_repo", "team_repo.team_id = team.id").
And("team_repo.org_id = ?", orgID).
And("team_repo.repo_id = ?", repoID).
Find(&teams)
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/mocks_test.go | internal/database/mocks_test.go | // Code generated by go-mockgen 2.1.1; DO NOT EDIT.
//
// This file was generated by running `go-mockgen` at the root of this repository.
// To add additional mocks to this or another package, add a new entry to the
// mockgen.yaml file in the root of this repository.
package database
import "sync"
// MockLoginSourceFileStore is a mock implementation of the
// loginSourceFileStore interface (from the package
// gogs.io/gogs/internal/database) used for unit testing.
type MockLoginSourceFileStore struct {
// SaveFunc is an instance of a mock function object controlling the
// behavior of the method Save.
SaveFunc *LoginSourceFileStoreSaveFunc
// SetConfigFunc is an instance of a mock function object controlling
// the behavior of the method SetConfig.
SetConfigFunc *LoginSourceFileStoreSetConfigFunc
// SetGeneralFunc is an instance of a mock function object controlling
// the behavior of the method SetGeneral.
SetGeneralFunc *LoginSourceFileStoreSetGeneralFunc
}
// NewMockLoginSourceFileStore creates a new mock of the
// loginSourceFileStore interface. All methods return zero values for all
// results, unless overwritten.
func NewMockLoginSourceFileStore() *MockLoginSourceFileStore {
return &MockLoginSourceFileStore{
SaveFunc: &LoginSourceFileStoreSaveFunc{
defaultHook: func() (r0 error) {
return
},
},
SetConfigFunc: &LoginSourceFileStoreSetConfigFunc{
defaultHook: func(interface{}) (r0 error) {
return
},
},
SetGeneralFunc: &LoginSourceFileStoreSetGeneralFunc{
defaultHook: func(string, string) {
return
},
},
}
}
// NewStrictMockLoginSourceFileStore creates a new mock of the
// loginSourceFileStore interface. All methods panic on invocation, unless
// overwritten.
func NewStrictMockLoginSourceFileStore() *MockLoginSourceFileStore {
return &MockLoginSourceFileStore{
SaveFunc: &LoginSourceFileStoreSaveFunc{
defaultHook: func() error {
panic("unexpected invocation of MockLoginSourceFileStore.Save")
},
},
SetConfigFunc: &LoginSourceFileStoreSetConfigFunc{
defaultHook: func(interface{}) error {
panic("unexpected invocation of MockLoginSourceFileStore.SetConfig")
},
},
SetGeneralFunc: &LoginSourceFileStoreSetGeneralFunc{
defaultHook: func(string, string) {
panic("unexpected invocation of MockLoginSourceFileStore.SetGeneral")
},
},
}
}
// surrogateMockLoginSourceFileStore is a copy of the loginSourceFileStore
// interface (from the package gogs.io/gogs/internal/database). It is
// redefined here as it is unexported in the source package.
type surrogateMockLoginSourceFileStore interface {
Save() error
SetConfig(interface{}) error
SetGeneral(string, string)
}
// NewMockLoginSourceFileStoreFrom creates a new mock of the
// MockLoginSourceFileStore interface. All methods delegate to the given
// implementation, unless overwritten.
func NewMockLoginSourceFileStoreFrom(i surrogateMockLoginSourceFileStore) *MockLoginSourceFileStore {
return &MockLoginSourceFileStore{
SaveFunc: &LoginSourceFileStoreSaveFunc{
defaultHook: i.Save,
},
SetConfigFunc: &LoginSourceFileStoreSetConfigFunc{
defaultHook: i.SetConfig,
},
SetGeneralFunc: &LoginSourceFileStoreSetGeneralFunc{
defaultHook: i.SetGeneral,
},
}
}
// LoginSourceFileStoreSaveFunc describes the behavior when the Save method
// of the parent MockLoginSourceFileStore instance is invoked.
type LoginSourceFileStoreSaveFunc struct {
defaultHook func() error
hooks []func() error
history []LoginSourceFileStoreSaveFuncCall
mutex sync.Mutex
}
// Save delegates to the next hook function in the queue and stores the
// parameter and result values of this invocation.
func (m *MockLoginSourceFileStore) Save() error {
r0 := m.SaveFunc.nextHook()()
m.SaveFunc.appendCall(LoginSourceFileStoreSaveFuncCall{r0})
return r0
}
// SetDefaultHook sets function that is called when the Save method of the
// parent MockLoginSourceFileStore instance is invoked and the hook queue is
// empty.
func (f *LoginSourceFileStoreSaveFunc) SetDefaultHook(hook func() error) {
f.defaultHook = hook
}
// PushHook adds a function to the end of hook queue. Each invocation of the
// Save method of the parent MockLoginSourceFileStore instance invokes the
// hook at the front of the queue and discards it. After the queue is empty,
// the default hook function is invoked for any future action.
func (f *LoginSourceFileStoreSaveFunc) PushHook(hook func() error) {
f.mutex.Lock()
f.hooks = append(f.hooks, hook)
f.mutex.Unlock()
}
// SetDefaultReturn calls SetDefaultHook with a function that returns the
// given values.
func (f *LoginSourceFileStoreSaveFunc) SetDefaultReturn(r0 error) {
f.SetDefaultHook(func() error {
return r0
})
}
// PushReturn calls PushHook with a function that returns the given values.
func (f *LoginSourceFileStoreSaveFunc) PushReturn(r0 error) {
f.PushHook(func() error {
return r0
})
}
func (f *LoginSourceFileStoreSaveFunc) nextHook() func() error {
f.mutex.Lock()
defer f.mutex.Unlock()
if len(f.hooks) == 0 {
return f.defaultHook
}
hook := f.hooks[0]
f.hooks = f.hooks[1:]
return hook
}
func (f *LoginSourceFileStoreSaveFunc) appendCall(r0 LoginSourceFileStoreSaveFuncCall) {
f.mutex.Lock()
f.history = append(f.history, r0)
f.mutex.Unlock()
}
// History returns a sequence of LoginSourceFileStoreSaveFuncCall objects
// describing the invocations of this function.
func (f *LoginSourceFileStoreSaveFunc) History() []LoginSourceFileStoreSaveFuncCall {
f.mutex.Lock()
history := make([]LoginSourceFileStoreSaveFuncCall, len(f.history))
copy(history, f.history)
f.mutex.Unlock()
return history
}
// LoginSourceFileStoreSaveFuncCall is an object that describes an
// invocation of method Save on an instance of MockLoginSourceFileStore.
type LoginSourceFileStoreSaveFuncCall struct {
// Result0 is the value of the 1st result returned from this method
// invocation.
Result0 error
}
// Args returns an interface slice containing the arguments of this
// invocation.
func (c LoginSourceFileStoreSaveFuncCall) Args() []interface{} {
return []interface{}{}
}
// Results returns an interface slice containing the results of this
// invocation.
func (c LoginSourceFileStoreSaveFuncCall) Results() []interface{} {
return []interface{}{c.Result0}
}
// LoginSourceFileStoreSetConfigFunc describes the behavior when the
// SetConfig method of the parent MockLoginSourceFileStore instance is
// invoked.
type LoginSourceFileStoreSetConfigFunc struct {
defaultHook func(interface{}) error
hooks []func(interface{}) error
history []LoginSourceFileStoreSetConfigFuncCall
mutex sync.Mutex
}
// SetConfig delegates to the next hook function in the queue and stores the
// parameter and result values of this invocation.
func (m *MockLoginSourceFileStore) SetConfig(v0 interface{}) error {
r0 := m.SetConfigFunc.nextHook()(v0)
m.SetConfigFunc.appendCall(LoginSourceFileStoreSetConfigFuncCall{v0, r0})
return r0
}
// SetDefaultHook sets function that is called when the SetConfig method of
// the parent MockLoginSourceFileStore instance is invoked and the hook
// queue is empty.
func (f *LoginSourceFileStoreSetConfigFunc) SetDefaultHook(hook func(interface{}) error) {
f.defaultHook = hook
}
// PushHook adds a function to the end of hook queue. Each invocation of the
// SetConfig method of the parent MockLoginSourceFileStore instance invokes
// the hook at the front of the queue and discards it. After the queue is
// empty, the default hook function is invoked for any future action.
func (f *LoginSourceFileStoreSetConfigFunc) PushHook(hook func(interface{}) error) {
f.mutex.Lock()
f.hooks = append(f.hooks, hook)
f.mutex.Unlock()
}
// SetDefaultReturn calls SetDefaultHook with a function that returns the
// given values.
func (f *LoginSourceFileStoreSetConfigFunc) SetDefaultReturn(r0 error) {
f.SetDefaultHook(func(interface{}) error {
return r0
})
}
// PushReturn calls PushHook with a function that returns the given values.
func (f *LoginSourceFileStoreSetConfigFunc) PushReturn(r0 error) {
f.PushHook(func(interface{}) error {
return r0
})
}
func (f *LoginSourceFileStoreSetConfigFunc) nextHook() func(interface{}) error {
f.mutex.Lock()
defer f.mutex.Unlock()
if len(f.hooks) == 0 {
return f.defaultHook
}
hook := f.hooks[0]
f.hooks = f.hooks[1:]
return hook
}
func (f *LoginSourceFileStoreSetConfigFunc) appendCall(r0 LoginSourceFileStoreSetConfigFuncCall) {
f.mutex.Lock()
f.history = append(f.history, r0)
f.mutex.Unlock()
}
// History returns a sequence of LoginSourceFileStoreSetConfigFuncCall
// objects describing the invocations of this function.
func (f *LoginSourceFileStoreSetConfigFunc) History() []LoginSourceFileStoreSetConfigFuncCall {
f.mutex.Lock()
history := make([]LoginSourceFileStoreSetConfigFuncCall, len(f.history))
copy(history, f.history)
f.mutex.Unlock()
return history
}
// LoginSourceFileStoreSetConfigFuncCall is an object that describes an
// invocation of method SetConfig on an instance of
// MockLoginSourceFileStore.
type LoginSourceFileStoreSetConfigFuncCall struct {
// Arg0 is the value of the 1st argument passed to this method
// invocation.
Arg0 interface{}
// Result0 is the value of the 1st result returned from this method
// invocation.
Result0 error
}
// Args returns an interface slice containing the arguments of this
// invocation.
func (c LoginSourceFileStoreSetConfigFuncCall) Args() []interface{} {
return []interface{}{c.Arg0}
}
// Results returns an interface slice containing the results of this
// invocation.
func (c LoginSourceFileStoreSetConfigFuncCall) Results() []interface{} {
return []interface{}{c.Result0}
}
// LoginSourceFileStoreSetGeneralFunc describes the behavior when the
// SetGeneral method of the parent MockLoginSourceFileStore instance is
// invoked.
type LoginSourceFileStoreSetGeneralFunc struct {
defaultHook func(string, string)
hooks []func(string, string)
history []LoginSourceFileStoreSetGeneralFuncCall
mutex sync.Mutex
}
// SetGeneral delegates to the next hook function in the queue and stores
// the parameter and result values of this invocation.
func (m *MockLoginSourceFileStore) SetGeneral(v0 string, v1 string) {
m.SetGeneralFunc.nextHook()(v0, v1)
m.SetGeneralFunc.appendCall(LoginSourceFileStoreSetGeneralFuncCall{v0, v1})
return
}
// SetDefaultHook sets function that is called when the SetGeneral method of
// the parent MockLoginSourceFileStore instance is invoked and the hook
// queue is empty.
func (f *LoginSourceFileStoreSetGeneralFunc) SetDefaultHook(hook func(string, string)) {
f.defaultHook = hook
}
// PushHook adds a function to the end of hook queue. Each invocation of the
// SetGeneral method of the parent MockLoginSourceFileStore instance invokes
// the hook at the front of the queue and discards it. After the queue is
// empty, the default hook function is invoked for any future action.
func (f *LoginSourceFileStoreSetGeneralFunc) PushHook(hook func(string, string)) {
f.mutex.Lock()
f.hooks = append(f.hooks, hook)
f.mutex.Unlock()
}
// SetDefaultReturn calls SetDefaultHook with a function that returns the
// given values.
func (f *LoginSourceFileStoreSetGeneralFunc) SetDefaultReturn() {
f.SetDefaultHook(func(string, string) {
return
})
}
// PushReturn calls PushHook with a function that returns the given values.
func (f *LoginSourceFileStoreSetGeneralFunc) PushReturn() {
f.PushHook(func(string, string) {
return
})
}
func (f *LoginSourceFileStoreSetGeneralFunc) nextHook() func(string, string) {
f.mutex.Lock()
defer f.mutex.Unlock()
if len(f.hooks) == 0 {
return f.defaultHook
}
hook := f.hooks[0]
f.hooks = f.hooks[1:]
return hook
}
func (f *LoginSourceFileStoreSetGeneralFunc) appendCall(r0 LoginSourceFileStoreSetGeneralFuncCall) {
f.mutex.Lock()
f.history = append(f.history, r0)
f.mutex.Unlock()
}
// History returns a sequence of LoginSourceFileStoreSetGeneralFuncCall
// objects describing the invocations of this function.
func (f *LoginSourceFileStoreSetGeneralFunc) History() []LoginSourceFileStoreSetGeneralFuncCall {
f.mutex.Lock()
history := make([]LoginSourceFileStoreSetGeneralFuncCall, len(f.history))
copy(history, f.history)
f.mutex.Unlock()
return history
}
// LoginSourceFileStoreSetGeneralFuncCall is an object that describes an
// invocation of method SetGeneral on an instance of
// MockLoginSourceFileStore.
type LoginSourceFileStoreSetGeneralFuncCall struct {
// Arg0 is the value of the 1st argument passed to this method
// invocation.
Arg0 string
// Arg1 is the value of the 2nd argument passed to this method
// invocation.
Arg1 string
}
// Args returns an interface slice containing the arguments of this
// invocation.
func (c LoginSourceFileStoreSetGeneralFuncCall) Args() []interface{} {
return []interface{}{c.Arg0, c.Arg1}
}
// Results returns an interface slice containing the results of this
// invocation.
func (c LoginSourceFileStoreSetGeneralFuncCall) Results() []interface{} {
return []interface{}{}
}
// MockLoginSourceFilesStore is a mock implementation of the
// loginSourceFilesStore interface (from the package
// gogs.io/gogs/internal/database) used for unit testing.
type MockLoginSourceFilesStore struct {
// GetByIDFunc is an instance of a mock function object controlling the
// behavior of the method GetByID.
GetByIDFunc *LoginSourceFilesStoreGetByIDFunc
// LenFunc is an instance of a mock function object controlling the
// behavior of the method Len.
LenFunc *LoginSourceFilesStoreLenFunc
// ListFunc is an instance of a mock function object controlling the
// behavior of the method List.
ListFunc *LoginSourceFilesStoreListFunc
// UpdateFunc is an instance of a mock function object controlling the
// behavior of the method Update.
UpdateFunc *LoginSourceFilesStoreUpdateFunc
}
// NewMockLoginSourceFilesStore creates a new mock of the
// loginSourceFilesStore interface. All methods return zero values for all
// results, unless overwritten.
func NewMockLoginSourceFilesStore() *MockLoginSourceFilesStore {
return &MockLoginSourceFilesStore{
GetByIDFunc: &LoginSourceFilesStoreGetByIDFunc{
defaultHook: func(int64) (r0 *LoginSource, r1 error) {
return
},
},
LenFunc: &LoginSourceFilesStoreLenFunc{
defaultHook: func() (r0 int) {
return
},
},
ListFunc: &LoginSourceFilesStoreListFunc{
defaultHook: func(ListLoginSourceOptions) (r0 []*LoginSource) {
return
},
},
UpdateFunc: &LoginSourceFilesStoreUpdateFunc{
defaultHook: func(*LoginSource) {
return
},
},
}
}
// NewStrictMockLoginSourceFilesStore creates a new mock of the
// loginSourceFilesStore interface. All methods panic on invocation, unless
// overwritten.
func NewStrictMockLoginSourceFilesStore() *MockLoginSourceFilesStore {
return &MockLoginSourceFilesStore{
GetByIDFunc: &LoginSourceFilesStoreGetByIDFunc{
defaultHook: func(int64) (*LoginSource, error) {
panic("unexpected invocation of MockLoginSourceFilesStore.GetByID")
},
},
LenFunc: &LoginSourceFilesStoreLenFunc{
defaultHook: func() int {
panic("unexpected invocation of MockLoginSourceFilesStore.Len")
},
},
ListFunc: &LoginSourceFilesStoreListFunc{
defaultHook: func(ListLoginSourceOptions) []*LoginSource {
panic("unexpected invocation of MockLoginSourceFilesStore.List")
},
},
UpdateFunc: &LoginSourceFilesStoreUpdateFunc{
defaultHook: func(*LoginSource) {
panic("unexpected invocation of MockLoginSourceFilesStore.Update")
},
},
}
}
// surrogateMockLoginSourceFilesStore is a copy of the loginSourceFilesStore
// interface (from the package gogs.io/gogs/internal/database). It is
// redefined here as it is unexported in the source package.
type surrogateMockLoginSourceFilesStore interface {
GetByID(int64) (*LoginSource, error)
Len() int
List(ListLoginSourceOptions) []*LoginSource
Update(*LoginSource)
}
// NewMockLoginSourceFilesStoreFrom creates a new mock of the
// MockLoginSourceFilesStore interface. All methods delegate to the given
// implementation, unless overwritten.
func NewMockLoginSourceFilesStoreFrom(i surrogateMockLoginSourceFilesStore) *MockLoginSourceFilesStore {
return &MockLoginSourceFilesStore{
GetByIDFunc: &LoginSourceFilesStoreGetByIDFunc{
defaultHook: i.GetByID,
},
LenFunc: &LoginSourceFilesStoreLenFunc{
defaultHook: i.Len,
},
ListFunc: &LoginSourceFilesStoreListFunc{
defaultHook: i.List,
},
UpdateFunc: &LoginSourceFilesStoreUpdateFunc{
defaultHook: i.Update,
},
}
}
// LoginSourceFilesStoreGetByIDFunc describes the behavior when the GetByID
// method of the parent MockLoginSourceFilesStore instance is invoked.
type LoginSourceFilesStoreGetByIDFunc struct {
defaultHook func(int64) (*LoginSource, error)
hooks []func(int64) (*LoginSource, error)
history []LoginSourceFilesStoreGetByIDFuncCall
mutex sync.Mutex
}
// GetByID delegates to the next hook function in the queue and stores the
// parameter and result values of this invocation.
func (m *MockLoginSourceFilesStore) GetByID(v0 int64) (*LoginSource, error) {
r0, r1 := m.GetByIDFunc.nextHook()(v0)
m.GetByIDFunc.appendCall(LoginSourceFilesStoreGetByIDFuncCall{v0, r0, r1})
return r0, r1
}
// SetDefaultHook sets function that is called when the GetByID method of
// the parent MockLoginSourceFilesStore instance is invoked and the hook
// queue is empty.
func (f *LoginSourceFilesStoreGetByIDFunc) SetDefaultHook(hook func(int64) (*LoginSource, error)) {
f.defaultHook = hook
}
// PushHook adds a function to the end of hook queue. Each invocation of the
// GetByID method of the parent MockLoginSourceFilesStore instance invokes
// the hook at the front of the queue and discards it. After the queue is
// empty, the default hook function is invoked for any future action.
func (f *LoginSourceFilesStoreGetByIDFunc) PushHook(hook func(int64) (*LoginSource, error)) {
f.mutex.Lock()
f.hooks = append(f.hooks, hook)
f.mutex.Unlock()
}
// SetDefaultReturn calls SetDefaultHook with a function that returns the
// given values.
func (f *LoginSourceFilesStoreGetByIDFunc) SetDefaultReturn(r0 *LoginSource, r1 error) {
f.SetDefaultHook(func(int64) (*LoginSource, error) {
return r0, r1
})
}
// PushReturn calls PushHook with a function that returns the given values.
func (f *LoginSourceFilesStoreGetByIDFunc) PushReturn(r0 *LoginSource, r1 error) {
f.PushHook(func(int64) (*LoginSource, error) {
return r0, r1
})
}
func (f *LoginSourceFilesStoreGetByIDFunc) nextHook() func(int64) (*LoginSource, error) {
f.mutex.Lock()
defer f.mutex.Unlock()
if len(f.hooks) == 0 {
return f.defaultHook
}
hook := f.hooks[0]
f.hooks = f.hooks[1:]
return hook
}
func (f *LoginSourceFilesStoreGetByIDFunc) appendCall(r0 LoginSourceFilesStoreGetByIDFuncCall) {
f.mutex.Lock()
f.history = append(f.history, r0)
f.mutex.Unlock()
}
// History returns a sequence of LoginSourceFilesStoreGetByIDFuncCall
// objects describing the invocations of this function.
func (f *LoginSourceFilesStoreGetByIDFunc) History() []LoginSourceFilesStoreGetByIDFuncCall {
f.mutex.Lock()
history := make([]LoginSourceFilesStoreGetByIDFuncCall, len(f.history))
copy(history, f.history)
f.mutex.Unlock()
return history
}
// LoginSourceFilesStoreGetByIDFuncCall is an object that describes an
// invocation of method GetByID on an instance of MockLoginSourceFilesStore.
type LoginSourceFilesStoreGetByIDFuncCall struct {
// Arg0 is the value of the 1st argument passed to this method
// invocation.
Arg0 int64
// Result0 is the value of the 1st result returned from this method
// invocation.
Result0 *LoginSource
// Result1 is the value of the 2nd result returned from this method
// invocation.
Result1 error
}
// Args returns an interface slice containing the arguments of this
// invocation.
func (c LoginSourceFilesStoreGetByIDFuncCall) Args() []interface{} {
return []interface{}{c.Arg0}
}
// Results returns an interface slice containing the results of this
// invocation.
func (c LoginSourceFilesStoreGetByIDFuncCall) Results() []interface{} {
return []interface{}{c.Result0, c.Result1}
}
// LoginSourceFilesStoreLenFunc describes the behavior when the Len method
// of the parent MockLoginSourceFilesStore instance is invoked.
type LoginSourceFilesStoreLenFunc struct {
defaultHook func() int
hooks []func() int
history []LoginSourceFilesStoreLenFuncCall
mutex sync.Mutex
}
// Len delegates to the next hook function in the queue and stores the
// parameter and result values of this invocation.
func (m *MockLoginSourceFilesStore) Len() int {
r0 := m.LenFunc.nextHook()()
m.LenFunc.appendCall(LoginSourceFilesStoreLenFuncCall{r0})
return r0
}
// SetDefaultHook sets function that is called when the Len method of the
// parent MockLoginSourceFilesStore instance is invoked and the hook queue
// is empty.
func (f *LoginSourceFilesStoreLenFunc) SetDefaultHook(hook func() int) {
f.defaultHook = hook
}
// PushHook adds a function to the end of hook queue. Each invocation of the
// Len method of the parent MockLoginSourceFilesStore instance invokes the
// hook at the front of the queue and discards it. After the queue is empty,
// the default hook function is invoked for any future action.
func (f *LoginSourceFilesStoreLenFunc) PushHook(hook func() int) {
f.mutex.Lock()
f.hooks = append(f.hooks, hook)
f.mutex.Unlock()
}
// SetDefaultReturn calls SetDefaultHook with a function that returns the
// given values.
func (f *LoginSourceFilesStoreLenFunc) SetDefaultReturn(r0 int) {
f.SetDefaultHook(func() int {
return r0
})
}
// PushReturn calls PushHook with a function that returns the given values.
func (f *LoginSourceFilesStoreLenFunc) PushReturn(r0 int) {
f.PushHook(func() int {
return r0
})
}
func (f *LoginSourceFilesStoreLenFunc) nextHook() func() int {
f.mutex.Lock()
defer f.mutex.Unlock()
if len(f.hooks) == 0 {
return f.defaultHook
}
hook := f.hooks[0]
f.hooks = f.hooks[1:]
return hook
}
func (f *LoginSourceFilesStoreLenFunc) appendCall(r0 LoginSourceFilesStoreLenFuncCall) {
f.mutex.Lock()
f.history = append(f.history, r0)
f.mutex.Unlock()
}
// History returns a sequence of LoginSourceFilesStoreLenFuncCall objects
// describing the invocations of this function.
func (f *LoginSourceFilesStoreLenFunc) History() []LoginSourceFilesStoreLenFuncCall {
f.mutex.Lock()
history := make([]LoginSourceFilesStoreLenFuncCall, len(f.history))
copy(history, f.history)
f.mutex.Unlock()
return history
}
// LoginSourceFilesStoreLenFuncCall is an object that describes an
// invocation of method Len on an instance of MockLoginSourceFilesStore.
type LoginSourceFilesStoreLenFuncCall struct {
// Result0 is the value of the 1st result returned from this method
// invocation.
Result0 int
}
// Args returns an interface slice containing the arguments of this
// invocation.
func (c LoginSourceFilesStoreLenFuncCall) Args() []interface{} {
return []interface{}{}
}
// Results returns an interface slice containing the results of this
// invocation.
func (c LoginSourceFilesStoreLenFuncCall) Results() []interface{} {
return []interface{}{c.Result0}
}
// LoginSourceFilesStoreListFunc describes the behavior when the List method
// of the parent MockLoginSourceFilesStore instance is invoked.
type LoginSourceFilesStoreListFunc struct {
defaultHook func(ListLoginSourceOptions) []*LoginSource
hooks []func(ListLoginSourceOptions) []*LoginSource
history []LoginSourceFilesStoreListFuncCall
mutex sync.Mutex
}
// List delegates to the next hook function in the queue and stores the
// parameter and result values of this invocation.
func (m *MockLoginSourceFilesStore) List(v0 ListLoginSourceOptions) []*LoginSource {
r0 := m.ListFunc.nextHook()(v0)
m.ListFunc.appendCall(LoginSourceFilesStoreListFuncCall{v0, r0})
return r0
}
// SetDefaultHook sets function that is called when the List method of the
// parent MockLoginSourceFilesStore instance is invoked and the hook queue
// is empty.
func (f *LoginSourceFilesStoreListFunc) SetDefaultHook(hook func(ListLoginSourceOptions) []*LoginSource) {
f.defaultHook = hook
}
// PushHook adds a function to the end of hook queue. Each invocation of the
// List method of the parent MockLoginSourceFilesStore instance invokes the
// hook at the front of the queue and discards it. After the queue is empty,
// the default hook function is invoked for any future action.
func (f *LoginSourceFilesStoreListFunc) PushHook(hook func(ListLoginSourceOptions) []*LoginSource) {
f.mutex.Lock()
f.hooks = append(f.hooks, hook)
f.mutex.Unlock()
}
// SetDefaultReturn calls SetDefaultHook with a function that returns the
// given values.
func (f *LoginSourceFilesStoreListFunc) SetDefaultReturn(r0 []*LoginSource) {
f.SetDefaultHook(func(ListLoginSourceOptions) []*LoginSource {
return r0
})
}
// PushReturn calls PushHook with a function that returns the given values.
func (f *LoginSourceFilesStoreListFunc) PushReturn(r0 []*LoginSource) {
f.PushHook(func(ListLoginSourceOptions) []*LoginSource {
return r0
})
}
func (f *LoginSourceFilesStoreListFunc) nextHook() func(ListLoginSourceOptions) []*LoginSource {
f.mutex.Lock()
defer f.mutex.Unlock()
if len(f.hooks) == 0 {
return f.defaultHook
}
hook := f.hooks[0]
f.hooks = f.hooks[1:]
return hook
}
func (f *LoginSourceFilesStoreListFunc) appendCall(r0 LoginSourceFilesStoreListFuncCall) {
f.mutex.Lock()
f.history = append(f.history, r0)
f.mutex.Unlock()
}
// History returns a sequence of LoginSourceFilesStoreListFuncCall objects
// describing the invocations of this function.
func (f *LoginSourceFilesStoreListFunc) History() []LoginSourceFilesStoreListFuncCall {
f.mutex.Lock()
history := make([]LoginSourceFilesStoreListFuncCall, len(f.history))
copy(history, f.history)
f.mutex.Unlock()
return history
}
// LoginSourceFilesStoreListFuncCall is an object that describes an
// invocation of method List on an instance of MockLoginSourceFilesStore.
type LoginSourceFilesStoreListFuncCall struct {
// Arg0 is the value of the 1st argument passed to this method
// invocation.
Arg0 ListLoginSourceOptions
// Result0 is the value of the 1st result returned from this method
// invocation.
Result0 []*LoginSource
}
// Args returns an interface slice containing the arguments of this
// invocation.
func (c LoginSourceFilesStoreListFuncCall) Args() []interface{} {
return []interface{}{c.Arg0}
}
// Results returns an interface slice containing the results of this
// invocation.
func (c LoginSourceFilesStoreListFuncCall) Results() []interface{} {
return []interface{}{c.Result0}
}
// LoginSourceFilesStoreUpdateFunc describes the behavior when the Update
// method of the parent MockLoginSourceFilesStore instance is invoked.
type LoginSourceFilesStoreUpdateFunc struct {
defaultHook func(*LoginSource)
hooks []func(*LoginSource)
history []LoginSourceFilesStoreUpdateFuncCall
mutex sync.Mutex
}
// Update delegates to the next hook function in the queue and stores the
// parameter and result values of this invocation.
func (m *MockLoginSourceFilesStore) Update(v0 *LoginSource) {
m.UpdateFunc.nextHook()(v0)
m.UpdateFunc.appendCall(LoginSourceFilesStoreUpdateFuncCall{v0})
return
}
// SetDefaultHook sets function that is called when the Update method of the
// parent MockLoginSourceFilesStore instance is invoked and the hook queue
// is empty.
func (f *LoginSourceFilesStoreUpdateFunc) SetDefaultHook(hook func(*LoginSource)) {
f.defaultHook = hook
}
// PushHook adds a function to the end of hook queue. Each invocation of the
// Update method of the parent MockLoginSourceFilesStore instance invokes
// the hook at the front of the queue and discards it. After the queue is
// empty, the default hook function is invoked for any future action.
func (f *LoginSourceFilesStoreUpdateFunc) PushHook(hook func(*LoginSource)) {
f.mutex.Lock()
f.hooks = append(f.hooks, hook)
f.mutex.Unlock()
}
// SetDefaultReturn calls SetDefaultHook with a function that returns the
// given values.
func (f *LoginSourceFilesStoreUpdateFunc) SetDefaultReturn() {
f.SetDefaultHook(func(*LoginSource) {
return
})
}
// PushReturn calls PushHook with a function that returns the given values.
func (f *LoginSourceFilesStoreUpdateFunc) PushReturn() {
f.PushHook(func(*LoginSource) {
return
})
}
func (f *LoginSourceFilesStoreUpdateFunc) nextHook() func(*LoginSource) {
f.mutex.Lock()
defer f.mutex.Unlock()
if len(f.hooks) == 0 {
return f.defaultHook
}
hook := f.hooks[0]
f.hooks = f.hooks[1:]
return hook
}
func (f *LoginSourceFilesStoreUpdateFunc) appendCall(r0 LoginSourceFilesStoreUpdateFuncCall) {
f.mutex.Lock()
f.history = append(f.history, r0)
f.mutex.Unlock()
}
// History returns a sequence of LoginSourceFilesStoreUpdateFuncCall objects
// describing the invocations of this function.
func (f *LoginSourceFilesStoreUpdateFunc) History() []LoginSourceFilesStoreUpdateFuncCall {
f.mutex.Lock()
history := make([]LoginSourceFilesStoreUpdateFuncCall, len(f.history))
copy(history, f.history)
f.mutex.Unlock()
return history
}
// LoginSourceFilesStoreUpdateFuncCall is an object that describes an
// invocation of method Update on an instance of MockLoginSourceFilesStore.
type LoginSourceFilesStoreUpdateFuncCall struct {
// Arg0 is the value of the 1st argument passed to this method
// invocation.
Arg0 *LoginSource
}
// Args returns an interface slice containing the arguments of this
// invocation.
func (c LoginSourceFilesStoreUpdateFuncCall) Args() []interface{} {
return []interface{}{c.Arg0}
}
// Results returns an interface slice containing the results of this
// invocation.
func (c LoginSourceFilesStoreUpdateFuncCall) Results() []interface{} {
return []interface{}{}
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/login_source_files_test.go | internal/database/login_source_files_test.go | // Copyright 2020 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gogs.io/gogs/internal/errutil"
)
func TestLoginSourceFiles_GetByID(t *testing.T) {
store := &loginSourceFiles{
sources: []*LoginSource{
{ID: 101},
},
}
t.Run("source does not exist", func(t *testing.T) {
_, err := store.GetByID(1)
wantErr := ErrLoginSourceNotExist{args: errutil.Args{"id": int64(1)}}
assert.Equal(t, wantErr, err)
})
t.Run("source exists", func(t *testing.T) {
source, err := store.GetByID(101)
require.NoError(t, err)
assert.Equal(t, int64(101), source.ID)
})
}
func TestLoginSourceFiles_Len(t *testing.T) {
store := &loginSourceFiles{
sources: []*LoginSource{
{ID: 101},
},
}
assert.Equal(t, 1, store.Len())
}
func TestLoginSourceFiles_List(t *testing.T) {
store := &loginSourceFiles{
sources: []*LoginSource{
{ID: 101, IsActived: true},
{ID: 102, IsActived: false},
},
}
t.Run("list all sources", func(t *testing.T) {
sources := store.List(ListLoginSourceOptions{})
assert.Equal(t, 2, len(sources), "number of sources")
})
t.Run("list only activated sources", func(t *testing.T) {
sources := store.List(ListLoginSourceOptions{OnlyActivated: true})
assert.Equal(t, 1, len(sources), "number of sources")
assert.Equal(t, int64(101), sources[0].ID)
})
}
func TestLoginSourceFiles_Update(t *testing.T) {
store := &loginSourceFiles{
sources: []*LoginSource{
{ID: 101, IsActived: true, IsDefault: true},
{ID: 102, IsActived: false},
},
clock: time.Now,
}
source102 := &LoginSource{
ID: 102,
IsActived: true,
IsDefault: true,
}
store.Update(source102)
assert.False(t, store.sources[0].IsDefault)
assert.True(t, store.sources[1].IsActived)
assert.True(t, store.sources[1].IsDefault)
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/wiki.go | internal/database/wiki.go | // Copyright 2015 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"fmt"
"net/url"
"os"
"path"
"path/filepath"
"strings"
"time"
"github.com/unknwon/com"
"github.com/gogs/git-module"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/repoutil"
"gogs.io/gogs/internal/sync"
)
var wikiWorkingPool = sync.NewExclusivePool()
// ToWikiPageURL formats a string to corresponding wiki URL name.
func ToWikiPageURL(name string) string {
return url.QueryEscape(name)
}
// ToWikiPageName formats a URL back to corresponding wiki page name,
// and removes leading characters './' to prevent changing files
// that are not belong to wiki repository.
func ToWikiPageName(urlString string) string {
name, _ := url.QueryUnescape(urlString)
return strings.ReplaceAll(strings.TrimLeft(path.Clean("/"+name), "/"), "/", " ")
}
// WikiCloneLink returns clone URLs of repository wiki.
//
// Deprecated: Use repoutil.NewCloneLink instead.
func (r *Repository) WikiCloneLink() (cl *repoutil.CloneLink) {
return r.cloneLink(true)
}
// WikiPath returns wiki data path by given user and repository name.
func WikiPath(userName, repoName string) string {
return filepath.Join(repoutil.UserPath(userName), strings.ToLower(repoName)+".wiki.git")
}
func (r *Repository) WikiPath() string {
return WikiPath(r.MustOwner().Name, r.Name)
}
// HasWiki returns true if repository has wiki.
func (r *Repository) HasWiki() bool {
return com.IsDir(r.WikiPath())
}
// InitWiki initializes a wiki for repository,
// it does nothing when repository already has wiki.
func (r *Repository) InitWiki() error {
if r.HasWiki() {
return nil
}
if err := git.Init(r.WikiPath(), git.InitOptions{Bare: true}); err != nil {
return fmt.Errorf("init repository: %v", err)
} else if err = createDelegateHooks(r.WikiPath()); err != nil {
return fmt.Errorf("createDelegateHooks: %v", err)
}
return nil
}
func (r *Repository) LocalWikiPath() string {
return filepath.Join(conf.Server.AppDataPath, "tmp", "local-wiki", com.ToStr(r.ID))
}
// UpdateLocalWiki makes sure the local copy of repository wiki is up-to-date.
func (r *Repository) UpdateLocalWiki() error {
return UpdateLocalCopyBranch(r.WikiPath(), r.LocalWikiPath(), "master", true)
}
func discardLocalWikiChanges(localPath string) error {
return discardLocalRepoBranchChanges(localPath, "master")
}
// updateWikiPage adds new page to repository wiki.
func (r *Repository) updateWikiPage(doer *User, oldTitle, title, content, message string, isNew bool) (err error) {
wikiWorkingPool.CheckIn(com.ToStr(r.ID))
defer wikiWorkingPool.CheckOut(com.ToStr(r.ID))
if err = r.InitWiki(); err != nil {
return fmt.Errorf("InitWiki: %v", err)
}
localPath := r.LocalWikiPath()
if err = discardLocalWikiChanges(localPath); err != nil {
return fmt.Errorf("discardLocalWikiChanges: %v", err)
} else if err = r.UpdateLocalWiki(); err != nil {
return fmt.Errorf("UpdateLocalWiki: %v", err)
}
title = ToWikiPageName(title)
filename := path.Join(localPath, title+".md")
// If not a new file, show perform update not create.
if isNew {
if com.IsExist(filename) {
return ErrWikiAlreadyExist{filename}
}
} else {
os.Remove(path.Join(localPath, oldTitle+".md"))
}
// SECURITY: if new file is a symlink to non-exist critical file,
// attack content can be written to the target file (e.g. authorized_keys2)
// as a new page operation.
// So we want to make sure the symlink is removed before write anything.
// The new file we created will be in normal text format.
os.Remove(filename)
if err = os.WriteFile(filename, []byte(content), 0666); err != nil {
return fmt.Errorf("WriteFile: %v", err)
}
if message == "" {
message = "Update page '" + title + "'"
}
if err = git.Add(localPath, git.AddOptions{All: true}); err != nil {
return fmt.Errorf("add all changes: %v", err)
}
err = git.CreateCommit(
localPath,
&git.Signature{
Name: doer.DisplayName(),
Email: doer.Email,
When: time.Now(),
},
message,
)
if err != nil {
return fmt.Errorf("commit changes: %v", err)
} else if err = git.Push(localPath, "origin", "master"); err != nil {
return fmt.Errorf("push: %v", err)
}
return nil
}
func (r *Repository) AddWikiPage(doer *User, title, content, message string) error {
return r.updateWikiPage(doer, "", title, content, message, true)
}
func (r *Repository) EditWikiPage(doer *User, oldTitle, title, content, message string) error {
return r.updateWikiPage(doer, oldTitle, title, content, message, false)
}
func (r *Repository) DeleteWikiPage(doer *User, title string) (err error) {
wikiWorkingPool.CheckIn(com.ToStr(r.ID))
defer wikiWorkingPool.CheckOut(com.ToStr(r.ID))
localPath := r.LocalWikiPath()
if err = discardLocalWikiChanges(localPath); err != nil {
return fmt.Errorf("discardLocalWikiChanges: %v", err)
} else if err = r.UpdateLocalWiki(); err != nil {
return fmt.Errorf("UpdateLocalWiki: %v", err)
}
title = ToWikiPageName(title)
filename := path.Join(localPath, title+".md")
os.Remove(filename)
message := "Delete page '" + title + "'"
if err = git.Add(localPath, git.AddOptions{All: true}); err != nil {
return fmt.Errorf("add all changes: %v", err)
}
err = git.CreateCommit(
localPath,
&git.Signature{
Name: doer.DisplayName(),
Email: doer.Email,
When: time.Now(),
},
message,
)
if err != nil {
return fmt.Errorf("commit changes: %v", err)
} else if err = git.Push(localPath, "origin", "master"); err != nil {
return fmt.Errorf("push: %v", err)
}
return nil
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/two_factors.go | internal/database/two_factors.go | // Copyright 2020 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"context"
"encoding/base64"
"fmt"
"strings"
"time"
"github.com/pkg/errors"
"gorm.io/gorm"
log "unknwon.dev/clog/v2"
"gogs.io/gogs/internal/cryptoutil"
"gogs.io/gogs/internal/errutil"
"gogs.io/gogs/internal/strutil"
)
// BeforeCreate implements the GORM create hook.
func (t *TwoFactor) BeforeCreate(tx *gorm.DB) error {
if t.CreatedUnix == 0 {
t.CreatedUnix = tx.NowFunc().Unix()
}
return nil
}
// AfterFind implements the GORM query hook.
func (t *TwoFactor) AfterFind(_ *gorm.DB) error {
t.Created = time.Unix(t.CreatedUnix, 0).Local()
return nil
}
// TwoFactorsStore is the storage layer for two-factor authentication settings.
type TwoFactorsStore struct {
db *gorm.DB
}
func newTwoFactorsStore(db *gorm.DB) *TwoFactorsStore {
return &TwoFactorsStore{db: db}
}
// Create creates a new 2FA token and recovery codes for given user. The "key"
// is used to encrypt and later decrypt given "secret", which should be
// configured in site-level and change of the "key" will break all existing 2FA
// tokens.
func (s *TwoFactorsStore) Create(ctx context.Context, userID int64, key, secret string) error {
encrypted, err := cryptoutil.AESGCMEncrypt(cryptoutil.MD5Bytes(key), []byte(secret))
if err != nil {
return errors.Wrap(err, "encrypt secret")
}
tf := &TwoFactor{
UserID: userID,
Secret: base64.StdEncoding.EncodeToString(encrypted),
}
recoveryCodes, err := generateRecoveryCodes(userID, 10)
if err != nil {
return errors.Wrap(err, "generate recovery codes")
}
return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
err := tx.Create(tf).Error
if err != nil {
return err
}
return tx.Create(&recoveryCodes).Error
})
}
var _ errutil.NotFound = (*ErrTwoFactorNotFound)(nil)
type ErrTwoFactorNotFound struct {
args errutil.Args
}
func IsErrTwoFactorNotFound(err error) bool {
return errors.As(err, &ErrTwoFactorNotFound{})
}
func (err ErrTwoFactorNotFound) Error() string {
return fmt.Sprintf("2FA does not found: %v", err.args)
}
func (ErrTwoFactorNotFound) NotFound() bool {
return true
}
// GetByUserID returns the 2FA token of given user. It returns
// ErrTwoFactorNotFound when not found.
func (s *TwoFactorsStore) GetByUserID(ctx context.Context, userID int64) (*TwoFactor, error) {
tf := new(TwoFactor)
err := s.db.WithContext(ctx).Where("user_id = ?", userID).First(tf).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrTwoFactorNotFound{args: errutil.Args{"userID": userID}}
}
return nil, err
}
return tf, nil
}
// IsEnabled returns true if the user has enabled 2FA.
func (s *TwoFactorsStore) IsEnabled(ctx context.Context, userID int64) bool {
var count int64
err := s.db.WithContext(ctx).Model(new(TwoFactor)).Where("user_id = ?", userID).Count(&count).Error
if err != nil {
log.Error("Failed to count two factors [user_id: %d]: %v", userID, err)
}
return count > 0
}
// generateRecoveryCodes generates N number of recovery codes for 2FA.
func generateRecoveryCodes(userID int64, n int) ([]*TwoFactorRecoveryCode, error) {
recoveryCodes := make([]*TwoFactorRecoveryCode, n)
for i := 0; i < n; i++ {
code, err := strutil.RandomChars(10)
if err != nil {
return nil, errors.Wrap(err, "generate random characters")
}
recoveryCodes[i] = &TwoFactorRecoveryCode{
UserID: userID,
Code: strings.ToLower(code[:5] + "-" + code[5:]),
}
}
return recoveryCodes, nil
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/webhook_dingtalk.go | internal/database/webhook_dingtalk.go | // Copyright 2017 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"fmt"
"strings"
jsoniter "github.com/json-iterator/go"
"github.com/pkg/errors"
"github.com/gogs/git-module"
api "github.com/gogs/go-gogs-client"
)
const (
DingtalkNotificationTitle = "Gogs Notification"
)
// Refer: https://open-doc.dingtalk.com/docs/doc.htm?treeId=257&articleId=105735&docType=1
type DingtalkActionCard struct {
Title string `json:"title"`
Text string `json:"text"`
HideAvatar string `json:"hideAvatar"`
BtnOrientation string `json:"btnOrientation"`
SingleTitle string `json:"singleTitle"`
SingleURL string `json:"singleURL"`
}
// Refer: https://open-doc.dingtalk.com/docs/doc.htm?treeId=257&articleId=105735&docType=1
type DingtalkAtObject struct {
AtMobiles []string `json:"atMobiles"`
IsAtAll bool `json:"isAtAll"`
}
// Refer: https://open-doc.dingtalk.com/docs/doc.htm?treeId=257&articleId=105735&docType=1
type DingtalkPayload struct {
MsgType string `json:"msgtype"`
At DingtalkAtObject `json:"at"`
ActionCard DingtalkActionCard `json:"actionCard"`
}
func (p *DingtalkPayload) JSONPayload() ([]byte, error) {
data, err := jsoniter.MarshalIndent(p, "", " ")
if err != nil {
return []byte{}, err
}
return data, nil
}
func NewDingtalkActionCard(singleTitle, singleURL string) DingtalkActionCard {
return DingtalkActionCard{
Title: DingtalkNotificationTitle,
SingleURL: singleURL,
SingleTitle: singleTitle,
}
}
// TODO: add content
func GetDingtalkPayload(p api.Payloader, event HookEventType) (payload *DingtalkPayload, err error) {
switch event {
case HookEventTypeCreate:
payload = getDingtalkCreatePayload(p.(*api.CreatePayload))
case HookEventTypeDelete:
payload = getDingtalkDeletePayload(p.(*api.DeletePayload))
case HookEventTypeFork:
payload = getDingtalkForkPayload(p.(*api.ForkPayload))
case HookEventTypePush:
payload = getDingtalkPushPayload(p.(*api.PushPayload))
case HookEventTypeIssues:
payload = getDingtalkIssuesPayload(p.(*api.IssuesPayload))
case HookEventTypeIssueComment:
payload = getDingtalkIssueCommentPayload(p.(*api.IssueCommentPayload))
case HookEventTypePullRequest:
payload = getDingtalkPullRequestPayload(p.(*api.PullRequestPayload))
case HookEventTypeRelease:
payload = getDingtalkReleasePayload(p.(*api.ReleasePayload))
default:
return nil, errors.Errorf("unexpected event %q", event)
}
return payload, nil
}
func getDingtalkCreatePayload(p *api.CreatePayload) *DingtalkPayload {
refName := git.RefShortName(p.Ref)
refType := strings.Title(p.RefType)
actionCard := NewDingtalkActionCard("View "+refType, p.Repo.HTMLURL+"/src/"+refName)
actionCard.Text += "# New " + refType + " Create Event"
actionCard.Text += "\n- Repo: **" + MarkdownLinkFormatter(p.Repo.HTMLURL, p.Repo.Name) + "**"
actionCard.Text += "\n- New " + refType + ": **" + MarkdownLinkFormatter(p.Repo.HTMLURL+"/src/"+refName, refName) + "**"
return &DingtalkPayload{
MsgType: "actionCard",
ActionCard: actionCard,
}
}
func getDingtalkDeletePayload(p *api.DeletePayload) *DingtalkPayload {
refName := git.RefShortName(p.Ref)
refType := strings.Title(p.RefType)
actionCard := NewDingtalkActionCard("View Repo", p.Repo.HTMLURL)
actionCard.Text += "# " + refType + " Delete Event"
actionCard.Text += "\n- Repo: **" + MarkdownLinkFormatter(p.Repo.HTMLURL, p.Repo.Name) + "**"
actionCard.Text += "\n- " + refType + ": **" + refName + "**"
return &DingtalkPayload{
MsgType: "actionCard",
ActionCard: actionCard,
}
}
func getDingtalkForkPayload(p *api.ForkPayload) *DingtalkPayload {
actionCard := NewDingtalkActionCard("View Fork", p.Forkee.HTMLURL)
actionCard.Text += "# Repo Fork Event"
actionCard.Text += "\n- From Repo: **" + MarkdownLinkFormatter(p.Repo.HTMLURL, p.Repo.Name) + "**"
actionCard.Text += "\n- To Repo: **" + MarkdownLinkFormatter(p.Forkee.HTMLURL, p.Forkee.FullName) + "**"
return &DingtalkPayload{
MsgType: "actionCard",
ActionCard: actionCard,
}
}
func getDingtalkPushPayload(p *api.PushPayload) *DingtalkPayload {
refName := git.RefShortName(p.Ref)
pusher := p.Pusher.FullName
if pusher == "" {
pusher = p.Pusher.UserName
}
var detail string
for i, commit := range p.Commits {
msg := strings.Split(commit.Message, "\n")[0]
commitLink := MarkdownLinkFormatter(commit.URL, commit.ID[:7])
detail += fmt.Sprintf("> %d. %s %s - %s\n", i, commitLink, commit.Author.Name, msg)
}
actionCard := NewDingtalkActionCard("View Changes", p.CompareURL)
actionCard.Text += "# Repo Push Event"
actionCard.Text += "\n- Repo: **" + MarkdownLinkFormatter(p.Repo.HTMLURL, p.Repo.Name) + "**"
actionCard.Text += "\n- Ref: **" + MarkdownLinkFormatter(p.Repo.HTMLURL+"/src/"+refName, refName) + "**"
actionCard.Text += "\n- Pusher: **" + pusher + "**"
actionCard.Text += "\n## " + fmt.Sprintf("Total %d commits(s)", len(p.Commits))
actionCard.Text += "\n" + detail
return &DingtalkPayload{
MsgType: "actionCard",
ActionCard: actionCard,
}
}
func getDingtalkIssuesPayload(p *api.IssuesPayload) *DingtalkPayload {
issueName := fmt.Sprintf("#%d %s", p.Index, p.Issue.Title)
issueURL := fmt.Sprintf("%s/issues/%d", p.Repository.HTMLURL, p.Index)
actionCard := NewDingtalkActionCard("View Issue", issueURL)
actionCard.Text += "# Issue Event " + strings.Title(string(p.Action))
actionCard.Text += "\n- Issue: **" + MarkdownLinkFormatter(issueURL, issueName) + "**"
switch p.Action {
case api.HOOK_ISSUE_ASSIGNED:
actionCard.Text += "\n- New Assignee: **" + p.Issue.Assignee.UserName + "**"
case api.HOOK_ISSUE_MILESTONED:
actionCard.Text += "\n- New Milestone: **" + p.Issue.Milestone.Title + "**"
case api.HOOK_ISSUE_LABEL_UPDATED:
if len(p.Issue.Labels) > 0 {
labels := make([]string, len(p.Issue.Labels))
for i, label := range p.Issue.Labels {
labels[i] = "**" + label.Name + "**"
}
actionCard.Text += "\n- Labels: " + strings.Join(labels, ",")
} else {
actionCard.Text += "\n- Labels: **empty**"
}
}
if p.Issue.Body != "" {
actionCard.Text += "\n> " + p.Issue.Body
}
return &DingtalkPayload{
MsgType: "actionCard",
ActionCard: actionCard,
}
}
func getDingtalkIssueCommentPayload(p *api.IssueCommentPayload) *DingtalkPayload {
issueName := fmt.Sprintf("#%d %s", p.Issue.Index, p.Issue.Title)
commentURL := fmt.Sprintf("%s/issues/%d", p.Repository.HTMLURL, p.Issue.Index)
if p.Action != api.HOOK_ISSUE_COMMENT_DELETED {
commentURL += "#" + CommentHashTag(p.Comment.ID)
}
issueURL := fmt.Sprintf("%s/issues/%d", p.Repository.HTMLURL, p.Issue.Index)
actionCard := NewDingtalkActionCard("View Issue Comment", commentURL)
actionCard.Text += "# Issue Comment " + strings.Title(string(p.Action))
actionCard.Text += "\n- Issue: " + MarkdownLinkFormatter(issueURL, issueName)
actionCard.Text += "\n- Comment content: "
actionCard.Text += "\n> " + p.Comment.Body
return &DingtalkPayload{
MsgType: "actionCard",
ActionCard: actionCard,
}
}
func getDingtalkPullRequestPayload(p *api.PullRequestPayload) *DingtalkPayload {
title := "# Pull Request " + strings.Title(string(p.Action))
if p.Action == api.HOOK_ISSUE_CLOSED && p.PullRequest.HasMerged {
title = "# Pull Request Merged"
}
pullRequestURL := fmt.Sprintf("%s/pulls/%d", p.Repository.HTMLURL, p.Index)
content := "- PR: " + MarkdownLinkFormatter(pullRequestURL, fmt.Sprintf("#%d %s", p.Index, p.PullRequest.Title))
switch p.Action {
case api.HOOK_ISSUE_ASSIGNED:
content += "\n- New Assignee: **" + p.PullRequest.Assignee.UserName + "**"
case api.HOOK_ISSUE_MILESTONED:
content += "\n- New Milestone: *" + p.PullRequest.Milestone.Title + "*"
case api.HOOK_ISSUE_LABEL_UPDATED:
labels := make([]string, len(p.PullRequest.Labels))
for i, label := range p.PullRequest.Labels {
labels[i] = "**" + label.Name + "**"
}
content += "\n- New Labels: " + strings.Join(labels, ",")
}
actionCard := NewDingtalkActionCard("View Pull Request", pullRequestURL)
actionCard.Text += title + "\n" + content
if p.Action == api.HOOK_ISSUE_OPENED || p.Action == api.HOOK_ISSUE_EDITED {
actionCard.Text += "\n> " + p.PullRequest.Body
}
return &DingtalkPayload{
MsgType: "actionCard",
ActionCard: actionCard,
}
}
func getDingtalkReleasePayload(p *api.ReleasePayload) *DingtalkPayload {
releaseURL := p.Repository.HTMLURL + "/src/" + p.Release.TagName
author := p.Release.Author.FullName
if author == "" {
author = p.Release.Author.UserName
}
actionCard := NewDingtalkActionCard("View Release", releaseURL)
actionCard.Text += "# New Release Published"
actionCard.Text += "\n- Repo: " + MarkdownLinkFormatter(p.Repository.HTMLURL, p.Repository.Name)
actionCard.Text += "\n- Tag: " + MarkdownLinkFormatter(releaseURL, p.Release.TagName)
actionCard.Text += "\n- Author: " + author
actionCard.Text += fmt.Sprintf("\n- Draft?: %t", p.Release.Draft)
actionCard.Text += fmt.Sprintf("\n- Pre Release?: %t", p.Release.Prerelease)
actionCard.Text += "\n- Title: " + p.Release.Name
if p.Release.Body != "" {
actionCard.Text += "\n- Note: " + p.Release.Body
}
return &DingtalkPayload{
MsgType: "actionCard",
ActionCard: actionCard,
}
}
// MarkdownLinkFormatter formats link address and title into Markdown style.
func MarkdownLinkFormatter(link, text string) string {
return "[" + text + "](" + link + ")"
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/repo.go | internal/database/repo.go | // Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"bytes"
"context"
"fmt"
"image"
_ "image/jpeg"
"image/png"
"os"
"os/exec"
"path"
"path/filepath"
"sort"
"strings"
"time"
"github.com/nfnt/resize"
"github.com/pkg/errors"
"github.com/unknwon/cae/zip"
"github.com/unknwon/com"
"gopkg.in/ini.v1"
log "unknwon.dev/clog/v2"
"xorm.io/xorm"
"github.com/gogs/git-module"
api "github.com/gogs/go-gogs-client"
embedConf "gogs.io/gogs/conf"
"gogs.io/gogs/internal/avatar"
"gogs.io/gogs/internal/conf"
dberrors "gogs.io/gogs/internal/database/errors"
"gogs.io/gogs/internal/dbutil"
"gogs.io/gogs/internal/errutil"
"gogs.io/gogs/internal/markup"
"gogs.io/gogs/internal/osutil"
"gogs.io/gogs/internal/process"
"gogs.io/gogs/internal/repoutil"
"gogs.io/gogs/internal/semverutil"
"gogs.io/gogs/internal/sync"
)
// RepoAvatarURLPrefix is used to identify a URL is to access repository avatar.
const RepoAvatarURLPrefix = "repo-avatars"
var repoWorkingPool = sync.NewExclusivePool()
var (
Gitignores, Licenses, Readmes, LabelTemplates []string
// Maximum items per page in forks, watchers and stars of a repo
ItemsPerPage = 40
)
func LoadRepoConfig() {
// Load .gitignore and license files and readme templates.
types := []string{"gitignore", "license", "readme", "label"}
typeFiles := make([][]string, 4)
for i, t := range types {
files, err := embedConf.FileNames(t)
if err != nil {
log.Fatal("Failed to get %q files: %v", t, err)
}
customPath := filepath.Join(conf.CustomDir(), "conf", t)
if com.IsDir(customPath) {
customFiles, err := com.StatDir(customPath)
if err != nil {
log.Fatal("Failed to get custom %s files: %v", t, err)
}
for _, f := range customFiles {
if !com.IsSliceContainsStr(files, f) {
files = append(files, f)
}
}
}
typeFiles[i] = files
}
Gitignores = typeFiles[0]
Licenses = typeFiles[1]
Readmes = typeFiles[2]
LabelTemplates = typeFiles[3]
sort.Strings(Gitignores)
sort.Strings(Licenses)
sort.Strings(Readmes)
sort.Strings(LabelTemplates)
// Filter out invalid names and promote preferred licenses.
sortedLicenses := make([]string, 0, len(Licenses))
for _, name := range conf.Repository.PreferredLicenses {
if com.IsSliceContainsStr(Licenses, name) {
sortedLicenses = append(sortedLicenses, name)
}
}
for _, name := range Licenses {
if !com.IsSliceContainsStr(conf.Repository.PreferredLicenses, name) {
sortedLicenses = append(sortedLicenses, name)
}
}
Licenses = sortedLicenses
}
func NewRepoContext() {
zip.Verbose = false
// Check Git installation.
if _, err := exec.LookPath("git"); err != nil {
log.Fatal("Failed to test 'git' command: %v (forgotten install?)", err)
}
// Check Git version.
var err error
conf.Git.Version, err = git.BinVersion()
if err != nil {
log.Fatal("Failed to get Git version: %v", err)
}
log.Trace("Git version: %s", conf.Git.Version)
if semverutil.Compare(conf.Git.Version, "<", "1.8.3") {
log.Fatal("Gogs requires Git version greater or equal to 1.8.3")
}
// Git requires setting user.name and user.email in order to commit changes.
for configKey, defaultValue := range map[string]string{"user.name": "Gogs", "user.email": "gogs@fake.local"} {
if stdout, stderr, err := process.Exec("NewRepoContext(get setting)", "git", "config", "--get", configKey); err != nil || strings.TrimSpace(stdout) == "" {
// ExitError indicates this config is not set
if _, ok := err.(*exec.ExitError); ok || strings.TrimSpace(stdout) == "" {
if _, stderr, gerr := process.Exec("NewRepoContext(set "+configKey+")", "git", "config", "--global", configKey, defaultValue); gerr != nil {
log.Fatal("Failed to set git %s(%s): %s", configKey, gerr, stderr)
}
log.Info("Git config %s set to %s", configKey, defaultValue)
} else {
log.Fatal("Failed to get git %s(%s): %s", configKey, err, stderr)
}
}
}
// Set git some configurations.
if _, stderr, err := process.Exec("NewRepoContext(git config --global core.quotepath false)",
"git", "config", "--global", "core.quotepath", "false"); err != nil {
log.Fatal("Failed to execute 'git config --global core.quotepath false': %v - %s", err, stderr)
}
RemoveAllWithNotice("Clean up repository temporary data", filepath.Join(conf.Server.AppDataPath, "tmp"))
}
// Repository contains information of a repository.
type Repository struct {
ID int64 `gorm:"primaryKey"`
OwnerID int64 `xorm:"UNIQUE(s)" gorm:"uniqueIndex:repo_owner_name_unique"`
Owner *User `xorm:"-" gorm:"-" json:"-"`
LowerName string `xorm:"UNIQUE(s) INDEX NOT NULL" gorm:"uniqueIndex:repo_owner_name_unique;index;not null"`
Name string `xorm:"INDEX NOT NULL" gorm:"index;not null"`
Description string `xorm:"VARCHAR(512)" gorm:"type:VARCHAR(512)"`
Website string
DefaultBranch string
Size int64 `xorm:"NOT NULL DEFAULT 0" gorm:"not null;default:0"`
UseCustomAvatar bool
// Counters
NumWatches int
NumStars int
NumForks int
NumIssues int
NumClosedIssues int
NumOpenIssues int `xorm:"-" gorm:"-" json:"-"`
NumPulls int
NumClosedPulls int
NumOpenPulls int `xorm:"-" gorm:"-" json:"-"`
NumMilestones int `xorm:"NOT NULL DEFAULT 0" gorm:"not null;default:0"`
NumClosedMilestones int `xorm:"NOT NULL DEFAULT 0" gorm:"not null;default:0"`
NumOpenMilestones int `xorm:"-" gorm:"-" json:"-"`
NumTags int `xorm:"-" gorm:"-" json:"-"`
IsPrivate bool
// TODO: When migrate to GORM, make sure to do a loose migration with `HasColumn` and `AddColumn`,
// see docs in https://gorm.io/docs/migration.html.
IsUnlisted bool `xorm:"NOT NULL DEFAULT false" gorm:"not null;default:FALSE"`
IsBare bool
IsMirror bool
*Mirror `xorm:"-" gorm:"-" json:"-"`
// Advanced settings
EnableWiki bool `xorm:"NOT NULL DEFAULT true" gorm:"not null;default:TRUE"`
AllowPublicWiki bool
EnableExternalWiki bool
ExternalWikiURL string
EnableIssues bool `xorm:"NOT NULL DEFAULT true" gorm:"not null;default:TRUE"`
AllowPublicIssues bool
EnableExternalTracker bool
ExternalTrackerURL string
ExternalTrackerFormat string
ExternalTrackerStyle string
ExternalMetas map[string]string `xorm:"-" gorm:"-" json:"-"`
EnablePulls bool `xorm:"NOT NULL DEFAULT true" gorm:"not null;default:TRUE"`
PullsIgnoreWhitespace bool `xorm:"NOT NULL DEFAULT false" gorm:"not null;default:FALSE"`
PullsAllowRebase bool `xorm:"NOT NULL DEFAULT false" gorm:"not null;default:FALSE"`
IsFork bool `xorm:"NOT NULL DEFAULT false" gorm:"not null;default:FALSE"`
ForkID int64
BaseRepo *Repository `xorm:"-" gorm:"-" json:"-"`
Created time.Time `xorm:"-" gorm:"-" json:"-"`
CreatedUnix int64
Updated time.Time `xorm:"-" gorm:"-" json:"-"`
UpdatedUnix int64
}
func (r *Repository) BeforeInsert() {
r.CreatedUnix = time.Now().Unix()
r.UpdatedUnix = r.CreatedUnix
}
func (r *Repository) AfterSet(colName string, _ xorm.Cell) {
switch colName {
case "default_branch":
// FIXME: use db migration to solve all at once.
if r.DefaultBranch == "" {
r.DefaultBranch = conf.Repository.DefaultBranch
}
case "num_closed_issues":
r.NumOpenIssues = r.NumIssues - r.NumClosedIssues
case "num_closed_pulls":
r.NumOpenPulls = r.NumPulls - r.NumClosedPulls
case "num_closed_milestones":
r.NumOpenMilestones = r.NumMilestones - r.NumClosedMilestones
case "external_tracker_style":
if r.ExternalTrackerStyle == "" {
r.ExternalTrackerStyle = markup.IssueNameStyleNumeric
}
case "created_unix":
r.Created = time.Unix(r.CreatedUnix, 0).Local()
case "updated_unix":
r.Updated = time.Unix(r.UpdatedUnix, 0)
}
}
func (r *Repository) loadAttributes(e Engine) (err error) {
if r.Owner == nil {
r.Owner, err = getUserByID(e, r.OwnerID)
if err != nil {
return fmt.Errorf("getUserByID [%d]: %v", r.OwnerID, err)
}
}
if r.IsFork && r.BaseRepo == nil {
r.BaseRepo, err = getRepositoryByID(e, r.ForkID)
if err != nil {
if IsErrRepoNotExist(err) {
r.IsFork = false
r.ForkID = 0
} else {
return fmt.Errorf("get fork repository by ID: %v", err)
}
}
}
return nil
}
func (r *Repository) LoadAttributes() error {
return r.loadAttributes(x)
}
// IsPartialPublic returns true if repository is public or allow public access to wiki or issues.
func (r *Repository) IsPartialPublic() bool {
return !r.IsPrivate || r.AllowPublicWiki || r.AllowPublicIssues
}
func (r *Repository) CanGuestViewWiki() bool {
return r.EnableWiki && !r.EnableExternalWiki && r.AllowPublicWiki
}
func (r *Repository) CanGuestViewIssues() bool {
return r.EnableIssues && !r.EnableExternalTracker && r.AllowPublicIssues
}
// MustOwner always returns a valid *User object to avoid conceptually impossible error handling.
// It creates a fake object that contains error details when error occurs.
func (r *Repository) MustOwner() *User {
return r.mustOwner(x)
}
func (r *Repository) FullName() string {
return r.MustOwner().Name + "/" + r.Name
}
// Deprecated: Use repoutil.HTMLURL instead.
func (r *Repository) HTMLURL() string {
return conf.Server.ExternalURL + r.FullName()
}
// CustomAvatarPath returns repository custom avatar file path.
func (r *Repository) CustomAvatarPath() string {
return filepath.Join(conf.Picture.RepositoryAvatarUploadPath, com.ToStr(r.ID))
}
// RelAvatarLink returns relative avatar link to the site domain,
// which includes app sub-url as prefix.
// Since Gravatar support not needed here - just check for image path.
func (r *Repository) RelAvatarLink() string {
defaultImgURL := ""
if !com.IsExist(r.CustomAvatarPath()) {
return defaultImgURL
}
return fmt.Sprintf("%s/%s/%d", conf.Server.Subpath, RepoAvatarURLPrefix, r.ID)
}
// AvatarLink returns repository avatar absolute link.
func (r *Repository) AvatarLink() string {
link := r.RelAvatarLink()
if link[0] == '/' && link[1] != '/' {
return conf.Server.ExternalURL + strings.TrimPrefix(link, conf.Server.Subpath)[1:]
}
return link
}
// UploadAvatar saves custom avatar for repository.
// FIXME: split uploads to different subdirs in case we have massive number of repositories.
func (r *Repository) UploadAvatar(data []byte) error {
img, _, err := image.Decode(bytes.NewReader(data))
if err != nil {
return fmt.Errorf("decode image: %v", err)
}
_ = os.MkdirAll(conf.Picture.RepositoryAvatarUploadPath, os.ModePerm)
fw, err := os.Create(r.CustomAvatarPath())
if err != nil {
return fmt.Errorf("create custom avatar directory: %v", err)
}
defer fw.Close()
m := resize.Resize(avatar.DefaultSize, avatar.DefaultSize, img, resize.NearestNeighbor)
if err = png.Encode(fw, m); err != nil {
return fmt.Errorf("encode image: %v", err)
}
return nil
}
// DeleteAvatar deletes the repository custom avatar.
func (r *Repository) DeleteAvatar() error {
log.Trace("DeleteAvatar [%d]: %s", r.ID, r.CustomAvatarPath())
if err := os.Remove(r.CustomAvatarPath()); err != nil {
return err
}
r.UseCustomAvatar = false
return UpdateRepository(r, false)
}
// This method assumes following fields have been assigned with valid values:
// Required - BaseRepo (if fork)
// Arguments that are allowed to be nil: permission
//
// Deprecated: Use APIFormat instead.
func (r *Repository) APIFormatLegacy(permission *api.Permission, user ...*User) *api.Repository {
cloneLink := r.CloneLink()
apiRepo := &api.Repository{
ID: r.ID,
Owner: r.Owner.APIFormat(),
Name: r.Name,
FullName: r.FullName(),
Description: r.Description,
Private: r.IsPrivate,
Fork: r.IsFork,
Empty: r.IsBare,
Mirror: r.IsMirror,
Size: r.Size,
HTMLURL: r.HTMLURL(),
SSHURL: cloneLink.SSH,
CloneURL: cloneLink.HTTPS,
Website: r.Website,
Stars: r.NumStars,
Forks: r.NumForks,
Watchers: r.NumWatches,
OpenIssues: r.NumOpenIssues,
DefaultBranch: r.DefaultBranch,
Created: r.Created,
Updated: r.Updated,
Permissions: permission,
// Reserved for go-gogs-client change
// AvatarUrl: r.AvatarLink(),
}
if r.IsFork {
p := &api.Permission{Pull: true}
if len(user) != 0 {
accessMode := Handle.Permissions().AccessMode(
context.TODO(),
user[0].ID,
r.ID,
AccessModeOptions{
OwnerID: r.OwnerID,
Private: r.IsPrivate,
},
)
p.Admin = accessMode >= AccessModeAdmin
p.Push = accessMode >= AccessModeWrite
}
apiRepo.Parent = r.BaseRepo.APIFormatLegacy(p)
}
return apiRepo
}
func (r *Repository) getOwner(e Engine) (err error) {
if r.Owner != nil {
return nil
}
r.Owner, err = getUserByID(e, r.OwnerID)
return err
}
func (r *Repository) GetOwner() error {
return r.getOwner(x)
}
func (r *Repository) mustOwner(e Engine) *User {
if err := r.getOwner(e); err != nil {
return &User{
Name: "error",
FullName: err.Error(),
}
}
return r.Owner
}
func (r *Repository) UpdateSize() error {
countObject, err := git.CountObjects(r.RepoPath())
if err != nil {
return fmt.Errorf("count repository objects: %v", err)
}
r.Size = countObject.Size + countObject.SizePack
if _, err = x.Id(r.ID).Cols("size").Update(r); err != nil {
return fmt.Errorf("update size: %v", err)
}
return nil
}
// ComposeMetas composes a map of metas for rendering SHA1 URL and external issue tracker URL.
func (r *Repository) ComposeMetas() map[string]string {
if r.ExternalMetas != nil {
return r.ExternalMetas
}
r.ExternalMetas = map[string]string{
"repoLink": r.Link(),
}
if r.EnableExternalTracker {
r.ExternalMetas["user"] = r.MustOwner().Name
r.ExternalMetas["repo"] = r.Name
r.ExternalMetas["format"] = r.ExternalTrackerFormat
switch r.ExternalTrackerStyle {
case markup.IssueNameStyleAlphanumeric:
r.ExternalMetas["style"] = markup.IssueNameStyleAlphanumeric
default:
r.ExternalMetas["style"] = markup.IssueNameStyleNumeric
}
}
return r.ExternalMetas
}
// DeleteWiki removes the actual and local copy of repository wiki.
func (r *Repository) DeleteWiki() {
wikiPaths := []string{r.WikiPath(), r.LocalWikiPath()}
for _, wikiPath := range wikiPaths {
RemoveAllWithNotice("Delete repository wiki", wikiPath)
}
}
// getUsersWithAccesMode returns users that have at least given access mode to the repository.
func (r *Repository) getUsersWithAccesMode(e Engine, mode AccessMode) (_ []*User, err error) {
if err = r.getOwner(e); err != nil {
return nil, err
}
accesses := make([]*Access, 0, 10)
if err = e.Where("repo_id = ? AND mode >= ?", r.ID, mode).Find(&accesses); err != nil {
return nil, err
}
// Leave a seat for owner itself to append later, but if owner is an organization
// and just waste 1 unit is cheaper than re-allocate memory once.
users := make([]*User, 0, len(accesses)+1)
if len(accesses) > 0 {
userIDs := make([]int64, len(accesses))
for i := 0; i < len(accesses); i++ {
userIDs[i] = accesses[i].UserID
}
if err = e.In("id", userIDs).Find(&users); err != nil {
return nil, err
}
// TODO(unknwon): Rely on AfterFind hook to sanitize user full name.
for _, u := range users {
u.FullName = markup.Sanitize(u.FullName)
}
}
if !r.Owner.IsOrganization() {
users = append(users, r.Owner)
}
return users, nil
}
// getAssignees returns a list of users who can be assigned to issues in this repository.
func (r *Repository) getAssignees(e Engine) (_ []*User, err error) {
return r.getUsersWithAccesMode(e, AccessModeRead)
}
// GetAssignees returns all users that have read access and can be assigned to issues
// of the repository,
func (r *Repository) GetAssignees() (_ []*User, err error) {
return r.getAssignees(x)
}
// GetAssigneeByID returns the user that has write access of repository by given ID.
func (r *Repository) GetAssigneeByID(userID int64) (*User, error) {
ctx := context.TODO()
if !Handle.Permissions().Authorize(
ctx,
userID,
r.ID,
AccessModeRead,
AccessModeOptions{
OwnerID: r.OwnerID,
Private: r.IsPrivate,
},
) {
return nil, ErrUserNotExist{args: errutil.Args{"userID": userID}}
}
return Handle.Users().GetByID(ctx, userID)
}
// GetWriters returns all users that have write access to the repository.
func (r *Repository) GetWriters() (_ []*User, err error) {
return r.getUsersWithAccesMode(x, AccessModeWrite)
}
// GetMilestoneByID returns the milestone belongs to repository by given ID.
func (r *Repository) GetMilestoneByID(milestoneID int64) (*Milestone, error) {
return GetMilestoneByRepoID(r.ID, milestoneID)
}
// IssueStats returns number of open and closed repository issues by given filter mode.
func (r *Repository) IssueStats(userID int64, filterMode FilterMode, isPull bool) (int64, int64) {
return GetRepoIssueStats(r.ID, userID, filterMode, isPull)
}
func (r *Repository) GetMirror() (err error) {
r.Mirror, err = GetMirrorByRepoID(r.ID)
return err
}
func (r *Repository) repoPath(e Engine) string {
return RepoPath(r.mustOwner(e).Name, r.Name)
}
// Deprecated: Use repoutil.RepositoryPath instead.
func (r *Repository) RepoPath() string {
return r.repoPath(x)
}
func (r *Repository) GitConfigPath() string {
return filepath.Join(r.RepoPath(), "config")
}
func (r *Repository) RelLink() string {
return "/" + r.FullName()
}
func (r *Repository) Link() string {
return conf.Server.Subpath + "/" + r.FullName()
}
// Deprecated: Use repoutil.ComparePath instead.
func (r *Repository) ComposeCompareURL(oldCommitID, newCommitID string) string {
return fmt.Sprintf("%s/%s/compare/%s...%s", r.MustOwner().Name, r.Name, oldCommitID, newCommitID)
}
func (r *Repository) HasAccess(userID int64) bool {
return Handle.Permissions().Authorize(context.TODO(), userID, r.ID, AccessModeRead,
AccessModeOptions{
OwnerID: r.OwnerID,
Private: r.IsPrivate,
},
)
}
func (r *Repository) IsOwnedBy(userID int64) bool {
return r.OwnerID == userID
}
// CanBeForked returns true if repository meets the requirements of being forked.
func (r *Repository) CanBeForked() bool {
return !r.IsBare
}
// CanEnablePulls returns true if repository meets the requirements of accepting pulls.
func (r *Repository) CanEnablePulls() bool {
return !r.IsMirror && !r.IsBare
}
// AllowPulls returns true if repository meets the requirements of accepting pulls and has them enabled.
func (r *Repository) AllowsPulls() bool {
return r.CanEnablePulls() && r.EnablePulls
}
func (r *Repository) IsBranchRequirePullRequest(name string) bool {
return IsBranchOfRepoRequirePullRequest(r.ID, name)
}
// CanEnableEditor returns true if repository meets the requirements of web editor.
func (r *Repository) CanEnableEditor() bool {
return !r.IsMirror
}
// FIXME: should have a mutex to prevent producing same index for two issues that are created
// closely enough.
func (r *Repository) NextIssueIndex() int64 {
return int64(r.NumIssues+r.NumPulls) + 1
}
func (r *Repository) LocalCopyPath() string {
return filepath.Join(conf.Server.AppDataPath, "tmp", "local-r", com.ToStr(r.ID))
}
// UpdateLocalCopy fetches latest changes of given branch from repoPath to localPath.
// It creates a new clone if local copy does not exist, but does not checks out to a
// specific branch if the local copy belongs to a wiki.
// For existing local copy, it checks out to target branch by default, and safe to
// assume subsequent operations are against target branch when caller has confidence
// about no race condition.
func UpdateLocalCopyBranch(repoPath, localPath, branch string, isWiki bool) (err error) {
if !osutil.IsExist(localPath) {
// Checkout to a specific branch fails when wiki is an empty repository.
if isWiki {
branch = ""
}
if err = git.Clone(repoPath, localPath, git.CloneOptions{
Branch: branch,
Timeout: time.Duration(conf.Git.Timeout.Clone) * time.Second,
}); err != nil {
return fmt.Errorf("git clone [branch: %s]: %v", branch, err)
}
return nil
}
gitRepo, err := git.Open(localPath)
if err != nil {
return fmt.Errorf("open repository: %v", err)
}
if err = gitRepo.Fetch(git.FetchOptions{
Prune: true,
}); err != nil {
return fmt.Errorf("fetch: %v", err)
}
if err = gitRepo.Checkout(branch); err != nil {
return fmt.Errorf("checkout [branch: %s]: %v", branch, err)
}
// Reset to align with remote in case of force push.
rev := "origin/" + branch
if err = gitRepo.Reset(rev, git.ResetOptions{
Hard: true,
}); err != nil {
return fmt.Errorf("reset [revision: %s]: %v", rev, err)
}
return nil
}
// UpdateLocalCopyBranch makes sure local copy of repository in given branch is up-to-date.
func (r *Repository) UpdateLocalCopyBranch(branch string) error {
return UpdateLocalCopyBranch(r.RepoPath(), r.LocalCopyPath(), branch, false)
}
// PatchPath returns corresponding patch file path of repository by given issue ID.
func (r *Repository) PatchPath(index int64) (string, error) {
if err := r.GetOwner(); err != nil {
return "", err
}
return filepath.Join(RepoPath(r.Owner.Name, r.Name), "pulls", com.ToStr(index)+".patch"), nil
}
// SavePatch saves patch data to corresponding location by given issue ID.
func (r *Repository) SavePatch(index int64, patch []byte) error {
patchPath, err := r.PatchPath(index)
if err != nil {
return fmt.Errorf("PatchPath: %v", err)
}
if err = os.MkdirAll(filepath.Dir(patchPath), os.ModePerm); err != nil {
return err
}
if err = os.WriteFile(patchPath, patch, 0644); err != nil {
return fmt.Errorf("WriteFile: %v", err)
}
return nil
}
func isRepositoryExist(e Engine, u *User, repoName string) (bool, error) {
has, err := e.Get(&Repository{
OwnerID: u.ID,
LowerName: strings.ToLower(repoName),
})
return has && com.IsDir(RepoPath(u.Name, repoName)), err
}
// IsRepositoryExist returns true if the repository with given name under user has already existed.
func IsRepositoryExist(u *User, repoName string) (bool, error) {
return isRepositoryExist(x, u, repoName)
}
// Deprecated: Use repoutil.NewCloneLink instead.
func (r *Repository) cloneLink(isWiki bool) *repoutil.CloneLink {
repoName := r.Name
if isWiki {
repoName += ".wiki"
}
r.Owner = r.MustOwner()
cl := new(repoutil.CloneLink)
if conf.SSH.Port != 22 {
cl.SSH = fmt.Sprintf("ssh://%s@%s:%d/%s/%s.git", conf.App.RunUser, conf.SSH.Domain, conf.SSH.Port, r.Owner.Name, repoName)
} else {
cl.SSH = fmt.Sprintf("%s@%s:%s/%s.git", conf.App.RunUser, conf.SSH.Domain, r.Owner.Name, repoName)
}
cl.HTTPS = repoutil.HTTPSCloneURL(r.Owner.Name, repoName)
return cl
}
// CloneLink returns clone URLs of repository.
//
// Deprecated: Use repoutil.NewCloneLink instead.
func (r *Repository) CloneLink() (cl *repoutil.CloneLink) {
return r.cloneLink(false)
}
type MigrateRepoOptions struct {
Name string
Description string
IsPrivate bool
IsUnlisted bool
IsMirror bool
RemoteAddr string
}
/*
- GitHub, GitLab, Gogs: *.wiki.git
- BitBucket: *.git/wiki
*/
var commonWikiURLSuffixes = []string{".wiki.git", ".git/wiki"}
// wikiRemoteURL returns accessible repository URL for wiki if exists.
// Otherwise, it returns an empty string.
func wikiRemoteURL(remote string) string {
remote = strings.TrimSuffix(remote, ".git")
for _, suffix := range commonWikiURLSuffixes {
wikiURL := remote + suffix
if git.IsURLAccessible(time.Minute, wikiURL) {
return wikiURL
}
}
return ""
}
// MigrateRepository migrates a existing repository from other project hosting.
func MigrateRepository(doer, owner *User, opts MigrateRepoOptions) (*Repository, error) {
repo, err := CreateRepository(doer, owner, CreateRepoOptionsLegacy{
Name: opts.Name,
Description: opts.Description,
IsPrivate: opts.IsPrivate,
IsUnlisted: opts.IsUnlisted,
IsMirror: opts.IsMirror,
})
if err != nil {
return nil, err
}
repoPath := RepoPath(owner.Name, opts.Name)
wikiPath := WikiPath(owner.Name, opts.Name)
if owner.IsOrganization() {
t, err := owner.GetOwnerTeam()
if err != nil {
return nil, err
}
repo.NumWatches = t.NumMembers
} else {
repo.NumWatches = 1
}
migrateTimeout := time.Duration(conf.Git.Timeout.Migrate) * time.Second
RemoveAllWithNotice("Repository path erase before creation", repoPath)
if err = git.Clone(opts.RemoteAddr, repoPath, git.CloneOptions{
Mirror: true,
Quiet: true,
Timeout: migrateTimeout,
}); err != nil {
return repo, fmt.Errorf("clone: %v", err)
}
wikiRemotePath := wikiRemoteURL(opts.RemoteAddr)
if len(wikiRemotePath) > 0 {
RemoveAllWithNotice("Repository wiki path erase before creation", wikiPath)
if err = git.Clone(wikiRemotePath, wikiPath, git.CloneOptions{
Mirror: true,
Quiet: true,
Timeout: migrateTimeout,
}); err != nil {
log.Error("Failed to clone wiki: %v", err)
RemoveAllWithNotice("Delete repository wiki for initialization failure", wikiPath)
}
}
// Check if repository is empty.
_, stderr, err := com.ExecCmdDir(repoPath, "git", "log", "-1")
if err != nil {
if strings.Contains(stderr, "fatal: bad default revision 'HEAD'") {
repo.IsBare = true
} else {
return repo, fmt.Errorf("check bare: %v - %s", err, stderr)
}
}
if !repo.IsBare {
// Try to get HEAD branch and set it as default branch.
gitRepo, err := git.Open(repoPath)
if err != nil {
return repo, fmt.Errorf("open repository: %v", err)
}
refspec, err := gitRepo.SymbolicRef()
if err != nil {
return repo, fmt.Errorf("get HEAD branch: %v", err)
}
repo.DefaultBranch = git.RefShortName(refspec)
if err = repo.UpdateSize(); err != nil {
log.Error("UpdateSize [repo_id: %d]: %v", repo.ID, err)
}
}
if opts.IsMirror {
if _, err = x.InsertOne(&Mirror{
RepoID: repo.ID,
Interval: conf.Mirror.DefaultInterval,
EnablePrune: true,
NextSync: time.Now().Add(time.Duration(conf.Mirror.DefaultInterval) * time.Hour),
}); err != nil {
return repo, fmt.Errorf("InsertOne: %v", err)
}
repo.IsMirror = true
return repo, UpdateRepository(repo, false)
}
return CleanUpMigrateInfo(repo)
}
// cleanUpMigrateGitConfig removes mirror info which prevents "push --all".
// This also removes possible user credentials.
func cleanUpMigrateGitConfig(configPath string) error {
cfg, err := ini.Load(configPath)
if err != nil {
return fmt.Errorf("open config file: %v", err)
}
cfg.DeleteSection("remote \"origin\"")
if err = cfg.SaveToIndent(configPath, "\t"); err != nil {
return fmt.Errorf("save config file: %v", err)
}
return nil
}
var hooksTpls = map[git.HookName]string{
"pre-receive": "#!/usr/bin/env %s\n\"%s\" hook --config='%s' pre-receive\n",
"update": "#!/usr/bin/env %s\n\"%s\" hook --config='%s' update $1 $2 $3\n",
"post-receive": "#!/usr/bin/env %s\n\"%s\" hook --config='%s' post-receive\n",
}
func createDelegateHooks(repoPath string) (err error) {
for _, name := range git.ServerSideHooks {
hookPath := filepath.Join(repoPath, "hooks", string(name))
if err = os.WriteFile(hookPath,
[]byte(fmt.Sprintf(hooksTpls[name], conf.Repository.ScriptType, conf.AppPath(), conf.CustomConf)),
os.ModePerm); err != nil {
return fmt.Errorf("create delegate hook '%s': %v", hookPath, err)
}
}
return nil
}
// Finish migrating repository and/or wiki with things that don't need to be done for mirrors.
func CleanUpMigrateInfo(repo *Repository) (*Repository, error) {
repoPath := repo.RepoPath()
if err := createDelegateHooks(repoPath); err != nil {
return repo, fmt.Errorf("createDelegateHooks: %v", err)
}
if repo.HasWiki() {
if err := createDelegateHooks(repo.WikiPath()); err != nil {
return repo, fmt.Errorf("createDelegateHooks.(wiki): %v", err)
}
}
if err := cleanUpMigrateGitConfig(repo.GitConfigPath()); err != nil {
return repo, fmt.Errorf("cleanUpMigrateGitConfig: %v", err)
}
if repo.HasWiki() {
if err := cleanUpMigrateGitConfig(path.Join(repo.WikiPath(), "config")); err != nil {
return repo, fmt.Errorf("cleanUpMigrateGitConfig.(wiki): %v", err)
}
}
return repo, UpdateRepository(repo, false)
}
// initRepoCommit temporarily changes with work directory.
func initRepoCommit(tmpPath string, sig *git.Signature) (err error) {
var stderr string
if _, stderr, err = process.ExecDir(-1,
tmpPath, fmt.Sprintf("initRepoCommit (git add): %s", tmpPath),
"git", "add", "--all"); err != nil {
return fmt.Errorf("git add: %s", stderr)
}
if _, stderr, err = process.ExecDir(-1,
tmpPath, fmt.Sprintf("initRepoCommit (git commit): %s", tmpPath),
"git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
"-m", "Initial commit"); err != nil {
return fmt.Errorf("git commit: %s", stderr)
}
if _, stderr, err = process.ExecDir(-1,
tmpPath, fmt.Sprintf("initRepoCommit (git push): %s", tmpPath),
"git", "push"); err != nil {
return fmt.Errorf("git push: %s", stderr)
}
return nil
}
type CreateRepoOptionsLegacy struct {
Name string
Description string
Gitignores string
License string
Readme string
IsPrivate bool
IsUnlisted bool
IsMirror bool
AutoInit bool
}
func getRepoInitFile(tp, name string) ([]byte, error) {
relPath := path.Join(tp, strings.TrimLeft(path.Clean("/"+name), "/"))
// Use custom file when available.
customPath := filepath.Join(conf.CustomDir(), "conf", relPath)
if osutil.IsFile(customPath) {
return os.ReadFile(customPath)
}
return embedConf.Files.ReadFile(relPath)
}
func prepareRepoCommit(repo *Repository, tmpDir, repoPath string, opts CreateRepoOptionsLegacy) error {
// Clone to temporary path and do the init commit.
err := git.Clone(repoPath, tmpDir, git.CloneOptions{})
if err != nil {
return errors.Wrap(err, "clone")
}
// README
data, err := getRepoInitFile("readme", opts.Readme)
if err != nil {
return fmt.Errorf("getRepoInitFile[%s]: %v", opts.Readme, err)
}
cloneLink := repo.CloneLink()
match := map[string]string{
"Name": repo.Name,
"Description": repo.Description,
"CloneURL.SSH": cloneLink.SSH,
"CloneURL.HTTPS": cloneLink.HTTPS,
}
if err = os.WriteFile(filepath.Join(tmpDir, "README.md"),
[]byte(com.Expand(string(data), match)), 0644); err != nil {
return fmt.Errorf("write README.md: %v", err)
}
// .gitignore
if len(opts.Gitignores) > 0 {
var buf bytes.Buffer
names := strings.Split(opts.Gitignores, ",")
for _, name := range names {
data, err = getRepoInitFile("gitignore", name)
if err != nil {
return fmt.Errorf("getRepoInitFile[%s]: %v", name, err)
}
buf.WriteString("# ---> " + name + "\n")
buf.Write(data)
buf.WriteString("\n")
}
if buf.Len() > 0 {
if err = os.WriteFile(filepath.Join(tmpDir, ".gitignore"), buf.Bytes(), 0644); err != nil {
return fmt.Errorf("write .gitignore: %v", err)
}
}
}
// LICENSE
if len(opts.License) > 0 {
data, err = getRepoInitFile("license", opts.License)
if err != nil {
return fmt.Errorf("getRepoInitFile[%s]: %v", opts.License, err)
}
if err = os.WriteFile(filepath.Join(tmpDir, "LICENSE"), data, 0644); err != nil {
return fmt.Errorf("write LICENSE: %v", err)
}
}
return nil
}
// initRepository performs initial commit with chosen setup files on behave of doer.
func initRepository(e Engine, repoPath string, doer *User, repo *Repository, opts CreateRepoOptionsLegacy) (err error) {
// Somehow the directory could exist.
if com.IsExist(repoPath) {
return fmt.Errorf("initRepository: path already exists: %s", repoPath)
}
// Init bare new repository.
if err = git.Init(repoPath, git.InitOptions{Bare: true}); err != nil {
return fmt.Errorf("init repository: %v", err)
} else if err = createDelegateHooks(repoPath); err != nil {
return fmt.Errorf("createDelegateHooks: %v", err)
}
// Set default branch
_, err = git.SymbolicRef(
repoPath,
git.SymbolicRefOptions{
Name: "HEAD",
Ref: git.RefsHeads + conf.Repository.DefaultBranch,
},
)
if err != nil {
return errors.Wrap(err, "set default branch")
}
tmpDir := filepath.Join(os.TempDir(), "gogs-"+repo.Name+"-"+com.ToStr(time.Now().Nanosecond()))
// Initialize repository according to user's choice.
if opts.AutoInit {
if err = os.MkdirAll(tmpDir, os.ModePerm); err != nil {
return err
}
defer RemoveAllWithNotice("Delete repository for auto-initialization", tmpDir)
if err = prepareRepoCommit(repo, tmpDir, repoPath, opts); err != nil {
return fmt.Errorf("prepareRepoCommit: %v", err)
}
// Apply changes and commit.
err = initRepoCommit(
tmpDir,
&git.Signature{
Name: doer.DisplayName(),
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | true |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/repo_editor_test.go | internal/database/repo_editor_test.go | // Copyright 2018 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestIsRepositoryGitPath(t *testing.T) {
tests := []struct {
path string
wantVal bool
}{
{path: ".git", wantVal: true},
{path: "./.git", wantVal: true},
{path: ".git/hooks/pre-commit", wantVal: true},
{path: ".git/hooks", wantVal: true},
{path: "dir/.git", wantVal: true},
// Case-insensitive file system
{path: ".Git", wantVal: true},
{path: "./.Git", wantVal: true},
{path: ".Git/hooks/pre-commit", wantVal: true},
{path: ".Git/hooks", wantVal: true},
{path: "dir/.Git", wantVal: true},
{path: ".gitignore", wantVal: false},
{path: "dir/.gitkeep", wantVal: false},
// Windows-specific
{path: `.git\`, wantVal: true},
{path: `.git\hooks\pre-commit`, wantVal: true},
{path: `.git\hooks`, wantVal: true},
{path: `dir\.git`, wantVal: true},
{path: `.\.git.`, wantVal: true},
{path: `.\.git.\`, wantVal: true},
{path: `.git.\hooks\pre-commit`, wantVal: true},
{path: `.git.\hooks`, wantVal: true},
{path: `dir\.git.`, wantVal: true},
{path: "./.git.", wantVal: true},
{path: "./.git./", wantVal: true},
{path: ".git./hooks/pre-commit", wantVal: true},
{path: ".git./hooks", wantVal: true},
{path: "dir/.git.", wantVal: true},
{path: `dir\.gitkeep`, wantVal: false},
}
for _, test := range tests {
t.Run(test.path, func(t *testing.T) {
assert.Equal(t, test.wantVal, isRepositoryGitPath(test.path))
})
}
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/backup.go | internal/database/backup.go | package database
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"os"
"path/filepath"
"reflect"
"strings"
"sync"
jsoniter "github.com/json-iterator/go"
"github.com/pkg/errors"
"gorm.io/gorm"
"gorm.io/gorm/schema"
log "unknwon.dev/clog/v2"
"xorm.io/core"
"xorm.io/xorm"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/osutil"
)
// getTableType returns the type name of a table definition without package name,
// e.g. *database.LFSObject -> LFSObject.
func getTableType(t any) string {
return strings.TrimPrefix(fmt.Sprintf("%T", t), "*database.")
}
// DumpDatabase dumps all data from database to file system in JSON Lines format.
func DumpDatabase(ctx context.Context, db *gorm.DB, dirPath string, verbose bool) error {
err := os.MkdirAll(dirPath, os.ModePerm)
if err != nil {
return err
}
err = dumpLegacyTables(ctx, dirPath, verbose)
if err != nil {
return errors.Wrap(err, "dump legacy tables")
}
for _, table := range Tables {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
tableName := getTableType(table)
if verbose {
log.Trace("Dumping table %q...", tableName)
}
err := func() error {
tableFile := filepath.Join(dirPath, tableName+".json")
f, err := os.Create(tableFile)
if err != nil {
return errors.Wrap(err, "create table file")
}
defer func() { _ = f.Close() }()
return dumpTable(ctx, db, table, f)
}()
if err != nil {
return errors.Wrapf(err, "dump table %q", tableName)
}
}
return nil
}
func dumpTable(ctx context.Context, db *gorm.DB, table any, w io.Writer) error {
query := db.WithContext(ctx).Model(table)
switch table.(type) {
case *LFSObject:
query = query.Order("repo_id, oid ASC")
default:
query = query.Order("id ASC")
}
rows, err := query.Rows()
if err != nil {
return errors.Wrap(err, "select rows")
}
defer func() { _ = rows.Close() }()
for rows.Next() {
elem := reflect.New(reflect.TypeOf(table).Elem()).Interface()
err = db.ScanRows(rows, elem)
if err != nil {
return errors.Wrap(err, "scan rows")
}
switch e := elem.(type) {
case *LFSObject:
e.CreatedAt = e.CreatedAt.UTC()
}
err = jsoniter.NewEncoder(w).Encode(elem)
if err != nil {
return errors.Wrap(err, "encode JSON")
}
}
return rows.Err()
}
func dumpLegacyTables(ctx context.Context, dirPath string, verbose bool) error {
// Purposely create a local variable to not modify global variable
legacyTables := append(legacyTables, new(Version))
for _, table := range legacyTables {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
tableName := getTableType(table)
if verbose {
log.Trace("Dumping table %q...", tableName)
}
tableFile := filepath.Join(dirPath, tableName+".json")
f, err := os.Create(tableFile)
if err != nil {
return fmt.Errorf("create JSON file: %v", err)
}
if err = x.Context(ctx).Asc("id").Iterate(table, func(idx int, bean any) (err error) {
return jsoniter.NewEncoder(f).Encode(bean)
}); err != nil {
_ = f.Close()
return fmt.Errorf("dump table '%s': %v", tableName, err)
}
_ = f.Close()
}
return nil
}
// ImportDatabase imports data from backup archive in JSON Lines format.
func ImportDatabase(ctx context.Context, db *gorm.DB, dirPath string, verbose bool) error {
err := importLegacyTables(ctx, dirPath, verbose)
if err != nil {
return errors.Wrap(err, "import legacy tables")
}
for _, table := range Tables {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
tableName := strings.TrimPrefix(fmt.Sprintf("%T", table), "*database.")
err := func() error {
tableFile := filepath.Join(dirPath, tableName+".json")
if !osutil.IsFile(tableFile) {
log.Info("Skipped table %q", tableName)
return nil
}
if verbose {
log.Trace("Importing table %q...", tableName)
}
f, err := os.Open(tableFile)
if err != nil {
return errors.Wrap(err, "open table file")
}
defer func() { _ = f.Close() }()
return importTable(ctx, db, table, f)
}()
if err != nil {
return errors.Wrapf(err, "import table %q", tableName)
}
}
return nil
}
func importTable(ctx context.Context, db *gorm.DB, table any, r io.Reader) error {
err := db.WithContext(ctx).Migrator().DropTable(table)
if err != nil {
return errors.Wrap(err, "drop table")
}
err = db.WithContext(ctx).Migrator().AutoMigrate(table)
if err != nil {
return errors.Wrap(err, "auto migrate")
}
s, err := schema.Parse(table, &sync.Map{}, db.NamingStrategy)
if err != nil {
return errors.Wrap(err, "parse schema")
}
rawTableName := s.Table
skipResetIDSeq := map[string]bool{
"lfs_object": true,
}
scanner := bufio.NewScanner(r)
for scanner.Scan() {
// PostgreSQL does not like the null characters (U+0000)
cleaned := bytes.ReplaceAll(scanner.Bytes(), []byte("\\u0000"), []byte(""))
elem := reflect.New(reflect.TypeOf(table).Elem()).Interface()
err = jsoniter.Unmarshal(cleaned, elem)
if err != nil {
return errors.Wrap(err, "unmarshal JSON to struct")
}
err = db.WithContext(ctx).Create(elem).Error
if err != nil {
return errors.Wrap(err, "create row")
}
}
// PostgreSQL needs manually reset table sequence for auto increment keys
if conf.UsePostgreSQL && !skipResetIDSeq[rawTableName] {
seqName := rawTableName + "_id_seq"
if err = db.WithContext(ctx).Exec(fmt.Sprintf(`SELECT setval('%s', COALESCE((SELECT MAX(id)+1 FROM "%s"), 1), false)`, seqName, rawTableName)).Error; err != nil {
return errors.Wrapf(err, "reset table %q.%q", rawTableName, seqName)
}
}
return nil
}
func importLegacyTables(ctx context.Context, dirPath string, verbose bool) error {
snakeMapper := core.SnakeMapper{}
skipInsertProcessors := map[string]bool{
"mirror": true,
"milestone": true,
}
// Purposely create a local variable to not modify global variable
legacyTables := append(legacyTables, new(Version))
for _, table := range legacyTables {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
tableName := strings.TrimPrefix(fmt.Sprintf("%T", table), "*database.")
tableFile := filepath.Join(dirPath, tableName+".json")
if !osutil.IsFile(tableFile) {
continue
}
if verbose {
log.Trace("Importing table %q...", tableName)
}
if err := x.DropTables(table); err != nil {
return fmt.Errorf("drop table %q: %v", tableName, err)
} else if err = x.Sync2(table); err != nil {
return fmt.Errorf("sync table %q: %v", tableName, err)
}
f, err := os.Open(tableFile)
if err != nil {
return fmt.Errorf("open JSON file: %v", err)
}
rawTableName := x.TableName(table)
_, isInsertProcessor := table.(xorm.BeforeInsertProcessor)
scanner := bufio.NewScanner(f)
for scanner.Scan() {
if err = jsoniter.Unmarshal(scanner.Bytes(), table); err != nil {
return fmt.Errorf("unmarshal to struct: %v", err)
}
if _, err = x.Insert(table); err != nil {
return fmt.Errorf("insert strcut: %v", err)
}
var meta struct {
ID int64
CreatedUnix int64
DeadlineUnix int64
ClosedDateUnix int64
}
if err = jsoniter.Unmarshal(scanner.Bytes(), &meta); err != nil {
log.Error("Failed to unmarshal to map: %v", err)
}
// Reset created_unix back to the date save in archive because Insert method updates its value
if isInsertProcessor && !skipInsertProcessors[rawTableName] {
if _, err = x.Exec("UPDATE `"+rawTableName+"` SET created_unix=? WHERE id=?", meta.CreatedUnix, meta.ID); err != nil {
log.Error("Failed to reset '%s.created_unix': %v", rawTableName, err)
}
}
switch rawTableName {
case "milestone":
if _, err = x.Exec("UPDATE `"+rawTableName+"` SET deadline_unix=?, closed_date_unix=? WHERE id=?", meta.DeadlineUnix, meta.ClosedDateUnix, meta.ID); err != nil {
log.Error("Failed to reset 'milestone.deadline_unix', 'milestone.closed_date_unix': %v", err)
}
}
}
// PostgreSQL needs manually reset table sequence for auto increment keys
if conf.UsePostgreSQL {
rawTableName := snakeMapper.Obj2Table(tableName)
seqName := rawTableName + "_id_seq"
if _, err = x.Exec(fmt.Sprintf(`SELECT setval('%s', COALESCE((SELECT MAX(id)+1 FROM "%s"), 1), false);`, seqName, rawTableName)); err != nil {
return fmt.Errorf("reset table %q' sequence: %v", rawTableName, err)
}
}
}
return nil
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/two_factor.go | internal/database/two_factor.go | // Copyright 2017 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"encoding/base64"
"fmt"
"time"
"github.com/pquerna/otp/totp"
"github.com/unknwon/com"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/cryptoutil"
)
// TwoFactor is a 2FA token of a user.
type TwoFactor struct {
ID int64 `gorm:"primaryKey"`
UserID int64 `xorm:"UNIQUE" gorm:"unique"`
Secret string
Created time.Time `xorm:"-" gorm:"-" json:"-"`
CreatedUnix int64
}
// ValidateTOTP returns true if given passcode is valid for two-factor authentication token.
// It also returns possible validation error.
func (t *TwoFactor) ValidateTOTP(passcode string) (bool, error) {
secret, err := base64.StdEncoding.DecodeString(t.Secret)
if err != nil {
return false, fmt.Errorf("DecodeString: %v", err)
}
decryptSecret, err := com.AESGCMDecrypt(cryptoutil.MD5Bytes(conf.Security.SecretKey), secret)
if err != nil {
return false, fmt.Errorf("AESGCMDecrypt: %v", err)
}
return totp.Validate(passcode, string(decryptSecret)), nil
}
// DeleteTwoFactor removes two-factor authentication token and recovery codes of given user.
func DeleteTwoFactor(userID int64) (err error) {
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if _, err = sess.Where("user_id = ?", userID).Delete(new(TwoFactor)); err != nil {
return fmt.Errorf("delete two-factor: %v", err)
} else if err = deleteRecoveryCodesByUserID(sess, userID); err != nil {
return fmt.Errorf("deleteRecoveryCodesByUserID: %v", err)
}
return sess.Commit()
}
// TwoFactorRecoveryCode represents a two-factor authentication recovery code.
type TwoFactorRecoveryCode struct {
ID int64
UserID int64
Code string `xorm:"VARCHAR(11)"`
IsUsed bool
}
// GetRecoveryCodesByUserID returns all recovery codes of given user.
func GetRecoveryCodesByUserID(userID int64) ([]*TwoFactorRecoveryCode, error) {
recoveryCodes := make([]*TwoFactorRecoveryCode, 0, 10)
return recoveryCodes, x.Where("user_id = ?", userID).Find(&recoveryCodes)
}
func deleteRecoveryCodesByUserID(e Engine, userID int64) error {
_, err := e.Where("user_id = ?", userID).Delete(new(TwoFactorRecoveryCode))
return err
}
// RegenerateRecoveryCodes regenerates new set of recovery codes for given user.
func RegenerateRecoveryCodes(userID int64) error {
recoveryCodes, err := generateRecoveryCodes(userID, 10)
if err != nil {
return fmt.Errorf("generateRecoveryCodes: %v", err)
}
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if err = deleteRecoveryCodesByUserID(sess, userID); err != nil {
return fmt.Errorf("deleteRecoveryCodesByUserID: %v", err)
} else if _, err = sess.Insert(recoveryCodes); err != nil {
return fmt.Errorf("insert new recovery codes: %v", err)
}
return sess.Commit()
}
type ErrTwoFactorRecoveryCodeNotFound struct {
Code string
}
func IsTwoFactorRecoveryCodeNotFound(err error) bool {
_, ok := err.(ErrTwoFactorRecoveryCodeNotFound)
return ok
}
func (err ErrTwoFactorRecoveryCodeNotFound) Error() string {
return fmt.Sprintf("two-factor recovery code does not found [code: %s]", err.Code)
}
// UseRecoveryCode validates recovery code of given user and marks it is used if valid.
func UseRecoveryCode(_ int64, code string) error {
recoveryCode := new(TwoFactorRecoveryCode)
has, err := x.Where("code = ?", code).And("is_used = ?", false).Get(recoveryCode)
if err != nil {
return fmt.Errorf("get unused code: %v", err)
} else if !has {
return ErrTwoFactorRecoveryCodeNotFound{Code: code}
}
recoveryCode.IsUsed = true
if _, err = x.Id(recoveryCode.ID).Cols("is_used").Update(recoveryCode); err != nil {
return fmt.Errorf("mark code as used: %v", err)
}
return nil
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/mocks_gen.go | internal/database/mocks_gen.go | // Code generated by go-mockgen 2.1.1; DO NOT EDIT.
//
// This file was generated by running `go-mockgen` at the root of this repository.
// To add additional mocks to this or another package, add a new entry to the
// mockgen.yaml file in the root of this repository.
package database
import (
"sync"
auth "gogs.io/gogs/internal/auth"
)
// MockProvider is a mock implementation of the Provider interface (from the
// package gogs.io/gogs/internal/auth) used for unit testing.
type MockProvider struct {
// AuthenticateFunc is an instance of a mock function object controlling
// the behavior of the method Authenticate.
AuthenticateFunc *ProviderAuthenticateFunc
// ConfigFunc is an instance of a mock function object controlling the
// behavior of the method Config.
ConfigFunc *ProviderConfigFunc
// HasTLSFunc is an instance of a mock function object controlling the
// behavior of the method HasTLS.
HasTLSFunc *ProviderHasTLSFunc
// SkipTLSVerifyFunc is an instance of a mock function object
// controlling the behavior of the method SkipTLSVerify.
SkipTLSVerifyFunc *ProviderSkipTLSVerifyFunc
// UseTLSFunc is an instance of a mock function object controlling the
// behavior of the method UseTLS.
UseTLSFunc *ProviderUseTLSFunc
}
// NewMockProvider creates a new mock of the Provider interface. All methods
// return zero values for all results, unless overwritten.
func NewMockProvider() *MockProvider {
return &MockProvider{
AuthenticateFunc: &ProviderAuthenticateFunc{
defaultHook: func(string, string) (r0 *auth.ExternalAccount, r1 error) {
return
},
},
ConfigFunc: &ProviderConfigFunc{
defaultHook: func() (r0 interface{}) {
return
},
},
HasTLSFunc: &ProviderHasTLSFunc{
defaultHook: func() (r0 bool) {
return
},
},
SkipTLSVerifyFunc: &ProviderSkipTLSVerifyFunc{
defaultHook: func() (r0 bool) {
return
},
},
UseTLSFunc: &ProviderUseTLSFunc{
defaultHook: func() (r0 bool) {
return
},
},
}
}
// NewStrictMockProvider creates a new mock of the Provider interface. All
// methods panic on invocation, unless overwritten.
func NewStrictMockProvider() *MockProvider {
return &MockProvider{
AuthenticateFunc: &ProviderAuthenticateFunc{
defaultHook: func(string, string) (*auth.ExternalAccount, error) {
panic("unexpected invocation of MockProvider.Authenticate")
},
},
ConfigFunc: &ProviderConfigFunc{
defaultHook: func() interface{} {
panic("unexpected invocation of MockProvider.Config")
},
},
HasTLSFunc: &ProviderHasTLSFunc{
defaultHook: func() bool {
panic("unexpected invocation of MockProvider.HasTLS")
},
},
SkipTLSVerifyFunc: &ProviderSkipTLSVerifyFunc{
defaultHook: func() bool {
panic("unexpected invocation of MockProvider.SkipTLSVerify")
},
},
UseTLSFunc: &ProviderUseTLSFunc{
defaultHook: func() bool {
panic("unexpected invocation of MockProvider.UseTLS")
},
},
}
}
// NewMockProviderFrom creates a new mock of the MockProvider interface. All
// methods delegate to the given implementation, unless overwritten.
func NewMockProviderFrom(i auth.Provider) *MockProvider {
return &MockProvider{
AuthenticateFunc: &ProviderAuthenticateFunc{
defaultHook: i.Authenticate,
},
ConfigFunc: &ProviderConfigFunc{
defaultHook: i.Config,
},
HasTLSFunc: &ProviderHasTLSFunc{
defaultHook: i.HasTLS,
},
SkipTLSVerifyFunc: &ProviderSkipTLSVerifyFunc{
defaultHook: i.SkipTLSVerify,
},
UseTLSFunc: &ProviderUseTLSFunc{
defaultHook: i.UseTLS,
},
}
}
// ProviderAuthenticateFunc describes the behavior when the Authenticate
// method of the parent MockProvider instance is invoked.
type ProviderAuthenticateFunc struct {
defaultHook func(string, string) (*auth.ExternalAccount, error)
hooks []func(string, string) (*auth.ExternalAccount, error)
history []ProviderAuthenticateFuncCall
mutex sync.Mutex
}
// Authenticate delegates to the next hook function in the queue and stores
// the parameter and result values of this invocation.
func (m *MockProvider) Authenticate(v0 string, v1 string) (*auth.ExternalAccount, error) {
r0, r1 := m.AuthenticateFunc.nextHook()(v0, v1)
m.AuthenticateFunc.appendCall(ProviderAuthenticateFuncCall{v0, v1, r0, r1})
return r0, r1
}
// SetDefaultHook sets function that is called when the Authenticate method
// of the parent MockProvider instance is invoked and the hook queue is
// empty.
func (f *ProviderAuthenticateFunc) SetDefaultHook(hook func(string, string) (*auth.ExternalAccount, error)) {
f.defaultHook = hook
}
// PushHook adds a function to the end of hook queue. Each invocation of the
// Authenticate method of the parent MockProvider instance invokes the hook
// at the front of the queue and discards it. After the queue is empty, the
// default hook function is invoked for any future action.
func (f *ProviderAuthenticateFunc) PushHook(hook func(string, string) (*auth.ExternalAccount, error)) {
f.mutex.Lock()
f.hooks = append(f.hooks, hook)
f.mutex.Unlock()
}
// SetDefaultReturn calls SetDefaultHook with a function that returns the
// given values.
func (f *ProviderAuthenticateFunc) SetDefaultReturn(r0 *auth.ExternalAccount, r1 error) {
f.SetDefaultHook(func(string, string) (*auth.ExternalAccount, error) {
return r0, r1
})
}
// PushReturn calls PushHook with a function that returns the given values.
func (f *ProviderAuthenticateFunc) PushReturn(r0 *auth.ExternalAccount, r1 error) {
f.PushHook(func(string, string) (*auth.ExternalAccount, error) {
return r0, r1
})
}
func (f *ProviderAuthenticateFunc) nextHook() func(string, string) (*auth.ExternalAccount, error) {
f.mutex.Lock()
defer f.mutex.Unlock()
if len(f.hooks) == 0 {
return f.defaultHook
}
hook := f.hooks[0]
f.hooks = f.hooks[1:]
return hook
}
func (f *ProviderAuthenticateFunc) appendCall(r0 ProviderAuthenticateFuncCall) {
f.mutex.Lock()
f.history = append(f.history, r0)
f.mutex.Unlock()
}
// History returns a sequence of ProviderAuthenticateFuncCall objects
// describing the invocations of this function.
func (f *ProviderAuthenticateFunc) History() []ProviderAuthenticateFuncCall {
f.mutex.Lock()
history := make([]ProviderAuthenticateFuncCall, len(f.history))
copy(history, f.history)
f.mutex.Unlock()
return history
}
// ProviderAuthenticateFuncCall is an object that describes an invocation of
// method Authenticate on an instance of MockProvider.
type ProviderAuthenticateFuncCall struct {
// Arg0 is the value of the 1st argument passed to this method
// invocation.
Arg0 string
// Arg1 is the value of the 2nd argument passed to this method
// invocation.
Arg1 string
// Result0 is the value of the 1st result returned from this method
// invocation.
Result0 *auth.ExternalAccount
// Result1 is the value of the 2nd result returned from this method
// invocation.
Result1 error
}
// Args returns an interface slice containing the arguments of this
// invocation.
func (c ProviderAuthenticateFuncCall) Args() []interface{} {
return []interface{}{c.Arg0, c.Arg1}
}
// Results returns an interface slice containing the results of this
// invocation.
func (c ProviderAuthenticateFuncCall) Results() []interface{} {
return []interface{}{c.Result0, c.Result1}
}
// ProviderConfigFunc describes the behavior when the Config method of the
// parent MockProvider instance is invoked.
type ProviderConfigFunc struct {
defaultHook func() interface{}
hooks []func() interface{}
history []ProviderConfigFuncCall
mutex sync.Mutex
}
// Config delegates to the next hook function in the queue and stores the
// parameter and result values of this invocation.
func (m *MockProvider) Config() interface{} {
r0 := m.ConfigFunc.nextHook()()
m.ConfigFunc.appendCall(ProviderConfigFuncCall{r0})
return r0
}
// SetDefaultHook sets function that is called when the Config method of the
// parent MockProvider instance is invoked and the hook queue is empty.
func (f *ProviderConfigFunc) SetDefaultHook(hook func() interface{}) {
f.defaultHook = hook
}
// PushHook adds a function to the end of hook queue. Each invocation of the
// Config method of the parent MockProvider instance invokes the hook at the
// front of the queue and discards it. After the queue is empty, the default
// hook function is invoked for any future action.
func (f *ProviderConfigFunc) PushHook(hook func() interface{}) {
f.mutex.Lock()
f.hooks = append(f.hooks, hook)
f.mutex.Unlock()
}
// SetDefaultReturn calls SetDefaultHook with a function that returns the
// given values.
func (f *ProviderConfigFunc) SetDefaultReturn(r0 interface{}) {
f.SetDefaultHook(func() interface{} {
return r0
})
}
// PushReturn calls PushHook with a function that returns the given values.
func (f *ProviderConfigFunc) PushReturn(r0 interface{}) {
f.PushHook(func() interface{} {
return r0
})
}
func (f *ProviderConfigFunc) nextHook() func() interface{} {
f.mutex.Lock()
defer f.mutex.Unlock()
if len(f.hooks) == 0 {
return f.defaultHook
}
hook := f.hooks[0]
f.hooks = f.hooks[1:]
return hook
}
func (f *ProviderConfigFunc) appendCall(r0 ProviderConfigFuncCall) {
f.mutex.Lock()
f.history = append(f.history, r0)
f.mutex.Unlock()
}
// History returns a sequence of ProviderConfigFuncCall objects describing
// the invocations of this function.
func (f *ProviderConfigFunc) History() []ProviderConfigFuncCall {
f.mutex.Lock()
history := make([]ProviderConfigFuncCall, len(f.history))
copy(history, f.history)
f.mutex.Unlock()
return history
}
// ProviderConfigFuncCall is an object that describes an invocation of
// method Config on an instance of MockProvider.
type ProviderConfigFuncCall struct {
// Result0 is the value of the 1st result returned from this method
// invocation.
Result0 interface{}
}
// Args returns an interface slice containing the arguments of this
// invocation.
func (c ProviderConfigFuncCall) Args() []interface{} {
return []interface{}{}
}
// Results returns an interface slice containing the results of this
// invocation.
func (c ProviderConfigFuncCall) Results() []interface{} {
return []interface{}{c.Result0}
}
// ProviderHasTLSFunc describes the behavior when the HasTLS method of the
// parent MockProvider instance is invoked.
type ProviderHasTLSFunc struct {
defaultHook func() bool
hooks []func() bool
history []ProviderHasTLSFuncCall
mutex sync.Mutex
}
// HasTLS delegates to the next hook function in the queue and stores the
// parameter and result values of this invocation.
func (m *MockProvider) HasTLS() bool {
r0 := m.HasTLSFunc.nextHook()()
m.HasTLSFunc.appendCall(ProviderHasTLSFuncCall{r0})
return r0
}
// SetDefaultHook sets function that is called when the HasTLS method of the
// parent MockProvider instance is invoked and the hook queue is empty.
func (f *ProviderHasTLSFunc) SetDefaultHook(hook func() bool) {
f.defaultHook = hook
}
// PushHook adds a function to the end of hook queue. Each invocation of the
// HasTLS method of the parent MockProvider instance invokes the hook at the
// front of the queue and discards it. After the queue is empty, the default
// hook function is invoked for any future action.
func (f *ProviderHasTLSFunc) PushHook(hook func() bool) {
f.mutex.Lock()
f.hooks = append(f.hooks, hook)
f.mutex.Unlock()
}
// SetDefaultReturn calls SetDefaultHook with a function that returns the
// given values.
func (f *ProviderHasTLSFunc) SetDefaultReturn(r0 bool) {
f.SetDefaultHook(func() bool {
return r0
})
}
// PushReturn calls PushHook with a function that returns the given values.
func (f *ProviderHasTLSFunc) PushReturn(r0 bool) {
f.PushHook(func() bool {
return r0
})
}
func (f *ProviderHasTLSFunc) nextHook() func() bool {
f.mutex.Lock()
defer f.mutex.Unlock()
if len(f.hooks) == 0 {
return f.defaultHook
}
hook := f.hooks[0]
f.hooks = f.hooks[1:]
return hook
}
func (f *ProviderHasTLSFunc) appendCall(r0 ProviderHasTLSFuncCall) {
f.mutex.Lock()
f.history = append(f.history, r0)
f.mutex.Unlock()
}
// History returns a sequence of ProviderHasTLSFuncCall objects describing
// the invocations of this function.
func (f *ProviderHasTLSFunc) History() []ProviderHasTLSFuncCall {
f.mutex.Lock()
history := make([]ProviderHasTLSFuncCall, len(f.history))
copy(history, f.history)
f.mutex.Unlock()
return history
}
// ProviderHasTLSFuncCall is an object that describes an invocation of
// method HasTLS on an instance of MockProvider.
type ProviderHasTLSFuncCall struct {
// Result0 is the value of the 1st result returned from this method
// invocation.
Result0 bool
}
// Args returns an interface slice containing the arguments of this
// invocation.
func (c ProviderHasTLSFuncCall) Args() []interface{} {
return []interface{}{}
}
// Results returns an interface slice containing the results of this
// invocation.
func (c ProviderHasTLSFuncCall) Results() []interface{} {
return []interface{}{c.Result0}
}
// ProviderSkipTLSVerifyFunc describes the behavior when the SkipTLSVerify
// method of the parent MockProvider instance is invoked.
type ProviderSkipTLSVerifyFunc struct {
defaultHook func() bool
hooks []func() bool
history []ProviderSkipTLSVerifyFuncCall
mutex sync.Mutex
}
// SkipTLSVerify delegates to the next hook function in the queue and stores
// the parameter and result values of this invocation.
func (m *MockProvider) SkipTLSVerify() bool {
r0 := m.SkipTLSVerifyFunc.nextHook()()
m.SkipTLSVerifyFunc.appendCall(ProviderSkipTLSVerifyFuncCall{r0})
return r0
}
// SetDefaultHook sets function that is called when the SkipTLSVerify method
// of the parent MockProvider instance is invoked and the hook queue is
// empty.
func (f *ProviderSkipTLSVerifyFunc) SetDefaultHook(hook func() bool) {
f.defaultHook = hook
}
// PushHook adds a function to the end of hook queue. Each invocation of the
// SkipTLSVerify method of the parent MockProvider instance invokes the hook
// at the front of the queue and discards it. After the queue is empty, the
// default hook function is invoked for any future action.
func (f *ProviderSkipTLSVerifyFunc) PushHook(hook func() bool) {
f.mutex.Lock()
f.hooks = append(f.hooks, hook)
f.mutex.Unlock()
}
// SetDefaultReturn calls SetDefaultHook with a function that returns the
// given values.
func (f *ProviderSkipTLSVerifyFunc) SetDefaultReturn(r0 bool) {
f.SetDefaultHook(func() bool {
return r0
})
}
// PushReturn calls PushHook with a function that returns the given values.
func (f *ProviderSkipTLSVerifyFunc) PushReturn(r0 bool) {
f.PushHook(func() bool {
return r0
})
}
func (f *ProviderSkipTLSVerifyFunc) nextHook() func() bool {
f.mutex.Lock()
defer f.mutex.Unlock()
if len(f.hooks) == 0 {
return f.defaultHook
}
hook := f.hooks[0]
f.hooks = f.hooks[1:]
return hook
}
func (f *ProviderSkipTLSVerifyFunc) appendCall(r0 ProviderSkipTLSVerifyFuncCall) {
f.mutex.Lock()
f.history = append(f.history, r0)
f.mutex.Unlock()
}
// History returns a sequence of ProviderSkipTLSVerifyFuncCall objects
// describing the invocations of this function.
func (f *ProviderSkipTLSVerifyFunc) History() []ProviderSkipTLSVerifyFuncCall {
f.mutex.Lock()
history := make([]ProviderSkipTLSVerifyFuncCall, len(f.history))
copy(history, f.history)
f.mutex.Unlock()
return history
}
// ProviderSkipTLSVerifyFuncCall is an object that describes an invocation
// of method SkipTLSVerify on an instance of MockProvider.
type ProviderSkipTLSVerifyFuncCall struct {
// Result0 is the value of the 1st result returned from this method
// invocation.
Result0 bool
}
// Args returns an interface slice containing the arguments of this
// invocation.
func (c ProviderSkipTLSVerifyFuncCall) Args() []interface{} {
return []interface{}{}
}
// Results returns an interface slice containing the results of this
// invocation.
func (c ProviderSkipTLSVerifyFuncCall) Results() []interface{} {
return []interface{}{c.Result0}
}
// ProviderUseTLSFunc describes the behavior when the UseTLS method of the
// parent MockProvider instance is invoked.
type ProviderUseTLSFunc struct {
defaultHook func() bool
hooks []func() bool
history []ProviderUseTLSFuncCall
mutex sync.Mutex
}
// UseTLS delegates to the next hook function in the queue and stores the
// parameter and result values of this invocation.
func (m *MockProvider) UseTLS() bool {
r0 := m.UseTLSFunc.nextHook()()
m.UseTLSFunc.appendCall(ProviderUseTLSFuncCall{r0})
return r0
}
// SetDefaultHook sets function that is called when the UseTLS method of the
// parent MockProvider instance is invoked and the hook queue is empty.
func (f *ProviderUseTLSFunc) SetDefaultHook(hook func() bool) {
f.defaultHook = hook
}
// PushHook adds a function to the end of hook queue. Each invocation of the
// UseTLS method of the parent MockProvider instance invokes the hook at the
// front of the queue and discards it. After the queue is empty, the default
// hook function is invoked for any future action.
func (f *ProviderUseTLSFunc) PushHook(hook func() bool) {
f.mutex.Lock()
f.hooks = append(f.hooks, hook)
f.mutex.Unlock()
}
// SetDefaultReturn calls SetDefaultHook with a function that returns the
// given values.
func (f *ProviderUseTLSFunc) SetDefaultReturn(r0 bool) {
f.SetDefaultHook(func() bool {
return r0
})
}
// PushReturn calls PushHook with a function that returns the given values.
func (f *ProviderUseTLSFunc) PushReturn(r0 bool) {
f.PushHook(func() bool {
return r0
})
}
func (f *ProviderUseTLSFunc) nextHook() func() bool {
f.mutex.Lock()
defer f.mutex.Unlock()
if len(f.hooks) == 0 {
return f.defaultHook
}
hook := f.hooks[0]
f.hooks = f.hooks[1:]
return hook
}
func (f *ProviderUseTLSFunc) appendCall(r0 ProviderUseTLSFuncCall) {
f.mutex.Lock()
f.history = append(f.history, r0)
f.mutex.Unlock()
}
// History returns a sequence of ProviderUseTLSFuncCall objects describing
// the invocations of this function.
func (f *ProviderUseTLSFunc) History() []ProviderUseTLSFuncCall {
f.mutex.Lock()
history := make([]ProviderUseTLSFuncCall, len(f.history))
copy(history, f.history)
f.mutex.Unlock()
return history
}
// ProviderUseTLSFuncCall is an object that describes an invocation of
// method UseTLS on an instance of MockProvider.
type ProviderUseTLSFuncCall struct {
// Result0 is the value of the 1st result returned from this method
// invocation.
Result0 bool
}
// Args returns an interface slice containing the arguments of this
// invocation.
func (c ProviderUseTLSFuncCall) Args() []interface{} {
return []interface{}{}
}
// Results returns an interface slice containing the results of this
// invocation.
func (c ProviderUseTLSFuncCall) Results() []interface{} {
return []interface{}{c.Result0}
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/public_keys.go | internal/database/public_keys.go | // Copyright 2023 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"os"
"path/filepath"
"github.com/pkg/errors"
"gorm.io/gorm"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/osutil"
)
// PublicKeysStore is the storage layer for public keys.
type PublicKeysStore struct {
db *gorm.DB
}
func newPublicKeysStore(db *gorm.DB) *PublicKeysStore {
return &PublicKeysStore{db: db}
}
func authorizedKeysPath() string {
return filepath.Join(conf.SSH.RootPath, "authorized_keys")
}
// RewriteAuthorizedKeys rewrites the "authorized_keys" file under the SSH root
// path with all public keys stored in the database.
func (s *PublicKeysStore) RewriteAuthorizedKeys() error {
sshOpLocker.Lock()
defer sshOpLocker.Unlock()
err := os.MkdirAll(conf.SSH.RootPath, os.ModePerm)
if err != nil {
return errors.Wrap(err, "create SSH root path")
}
fpath := authorizedKeysPath()
tempPath := fpath + ".tmp"
f, err := os.OpenFile(tempPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return errors.Wrap(err, "create temporary file")
}
defer func() {
_ = f.Close()
_ = os.Remove(tempPath)
}()
// NOTE: More recently updated keys are more likely to be used more frequently,
// putting them in the earlier lines could speed up the key lookup by SSHD.
rows, err := s.db.Model(&PublicKey{}).Order("updated_unix DESC").Rows()
if err != nil {
return errors.Wrap(err, "iterate public keys")
}
defer func() { _ = rows.Close() }()
for rows.Next() {
var key PublicKey
err = s.db.ScanRows(rows, &key)
if err != nil {
return errors.Wrap(err, "scan rows")
}
_, err = f.WriteString(key.AuthorizedString())
if err != nil {
return errors.Wrapf(err, "write key %d", key.ID)
}
}
if err = rows.Err(); err != nil {
return errors.Wrap(err, "check rows.Err")
}
err = f.Close()
if err != nil {
return errors.Wrap(err, "close temporary file")
}
if osutil.IsExist(fpath) {
err = os.Remove(fpath)
if err != nil {
return errors.Wrap(err, "remove")
}
}
err = os.Rename(tempPath, fpath)
if err != nil {
return errors.Wrap(err, "rename")
}
return nil
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/repo_test.go | internal/database/repo_test.go | package database
import (
"testing"
"github.com/stretchr/testify/assert"
"gogs.io/gogs/internal/markup"
)
func TestRepository_ComposeMetas(t *testing.T) {
repo := &Repository{
Name: "testrepo",
Owner: &User{
Name: "testuser",
},
ExternalTrackerFormat: "https://someurl.com/{user}/{repo}/{issue}",
}
t.Run("no external tracker is configured", func(t *testing.T) {
repo.EnableExternalTracker = false
metas := repo.ComposeMetas()
assert.Equal(t, metas["repoLink"], repo.Link())
// Should not have format and style if no external tracker is configured
_, ok := metas["format"]
assert.False(t, ok)
_, ok = metas["style"]
assert.False(t, ok)
})
t.Run("an external issue tracker is configured", func(t *testing.T) {
repo.ExternalMetas = nil
repo.EnableExternalTracker = true
// Default to numeric issue style
assert.Equal(t, markup.IssueNameStyleNumeric, repo.ComposeMetas()["style"])
repo.ExternalMetas = nil
repo.ExternalTrackerStyle = markup.IssueNameStyleNumeric
assert.Equal(t, markup.IssueNameStyleNumeric, repo.ComposeMetas()["style"])
repo.ExternalMetas = nil
repo.ExternalTrackerStyle = markup.IssueNameStyleAlphanumeric
assert.Equal(t, markup.IssueNameStyleAlphanumeric, repo.ComposeMetas()["style"])
repo.ExternalMetas = nil
metas := repo.ComposeMetas()
assert.Equal(t, "testuser", metas["user"])
assert.Equal(t, "testrepo", metas["repo"])
assert.Equal(t, "https://someurl.com/{user}/{repo}/{issue}", metas["format"])
})
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/pull.go | internal/database/pull.go | // Copyright 2015 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"context"
"fmt"
"os"
"path/filepath"
"time"
"github.com/unknwon/com"
log "unknwon.dev/clog/v2"
"xorm.io/xorm"
"github.com/gogs/git-module"
api "github.com/gogs/go-gogs-client"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/errutil"
"gogs.io/gogs/internal/osutil"
"gogs.io/gogs/internal/process"
"gogs.io/gogs/internal/sync"
)
var PullRequestQueue = sync.NewUniqueQueue(1000)
type PullRequestType int
const (
PullRequestTypeGogs PullRequestType = iota
PullRequestTypeGit
)
type PullRequestStatus int
const (
PullRequestStatusConflict PullRequestStatus = iota
PullRequestStatusChecking
PullRequestStatusMergeable
)
// PullRequest represents relation between pull request and repositories.
type PullRequest struct {
ID int64 `gorm:"primaryKey"`
Type PullRequestType
Status PullRequestStatus
IssueID int64 `xorm:"INDEX" gorm:"index"`
Issue *Issue `xorm:"-" json:"-" gorm:"-"`
Index int64
HeadRepoID int64
HeadRepo *Repository `xorm:"-" json:"-" gorm:"-"`
BaseRepoID int64
BaseRepo *Repository `xorm:"-" json:"-" gorm:"-"`
HeadUserName string
HeadBranch string
BaseBranch string
MergeBase string `xorm:"VARCHAR(40)" gorm:"type:VARCHAR(40)"`
HasMerged bool
MergedCommitID string `xorm:"VARCHAR(40)" gorm:"type:VARCHAR(40)"`
MergerID int64
Merger *User `xorm:"-" json:"-" gorm:"-"`
Merged time.Time `xorm:"-" json:"-" gorm:"-"`
MergedUnix int64
}
func (pr *PullRequest) BeforeUpdate() {
pr.MergedUnix = pr.Merged.Unix()
}
// Note: don't try to get Issue because will end up recursive querying.
func (pr *PullRequest) AfterSet(colName string, _ xorm.Cell) {
switch colName {
case "merged_unix":
if !pr.HasMerged {
return
}
pr.Merged = time.Unix(pr.MergedUnix, 0).Local()
}
}
// Note: don't try to get Issue because will end up recursive querying.
func (pr *PullRequest) loadAttributes(e Engine) (err error) {
if pr.HeadRepo == nil {
pr.HeadRepo, err = getRepositoryByID(e, pr.HeadRepoID)
if err != nil && !IsErrRepoNotExist(err) {
return fmt.Errorf("get head repository by ID: %v", err)
}
}
if pr.BaseRepo == nil {
pr.BaseRepo, err = getRepositoryByID(e, pr.BaseRepoID)
if err != nil {
return fmt.Errorf("get base repository by ID: %v", err)
}
}
if pr.HasMerged && pr.Merger == nil {
pr.Merger, err = getUserByID(e, pr.MergerID)
if IsErrUserNotExist(err) {
pr.MergerID = -1
pr.Merger = NewGhostUser()
} else if err != nil {
return fmt.Errorf("get merger by ID: %v", err)
}
}
return nil
}
func (pr *PullRequest) LoadAttributes() error {
return pr.loadAttributes(x)
}
func (pr *PullRequest) LoadIssue() (err error) {
if pr.Issue != nil {
return nil
}
pr.Issue, err = GetIssueByID(pr.IssueID)
return err
}
// This method assumes following fields have been assigned with valid values:
// Required - Issue, BaseRepo
// Optional - HeadRepo, Merger
func (pr *PullRequest) APIFormat() *api.PullRequest {
// In case of head repo has been deleted.
var apiHeadRepo *api.Repository
if pr.HeadRepo == nil {
apiHeadRepo = &api.Repository{
Name: "deleted",
}
} else {
apiHeadRepo = pr.HeadRepo.APIFormatLegacy(nil)
}
apiIssue := pr.Issue.APIFormat()
apiPullRequest := &api.PullRequest{
ID: pr.ID,
Index: pr.Index,
Poster: apiIssue.Poster,
Title: apiIssue.Title,
Body: apiIssue.Body,
Labels: apiIssue.Labels,
Milestone: apiIssue.Milestone,
Assignee: apiIssue.Assignee,
State: apiIssue.State,
Comments: apiIssue.Comments,
HeadBranch: pr.HeadBranch,
HeadRepo: apiHeadRepo,
BaseBranch: pr.BaseBranch,
BaseRepo: pr.BaseRepo.APIFormatLegacy(nil),
HTMLURL: pr.Issue.HTMLURL(),
HasMerged: pr.HasMerged,
}
if pr.Status != PullRequestStatusChecking {
mergeable := pr.Status != PullRequestStatusConflict
apiPullRequest.Mergeable = &mergeable
}
if pr.HasMerged {
apiPullRequest.Merged = &pr.Merged
apiPullRequest.MergedCommitID = &pr.MergedCommitID
apiPullRequest.MergedBy = pr.Merger.APIFormat()
}
return apiPullRequest
}
// IsChecking returns true if this pull request is still checking conflict.
func (pr *PullRequest) IsChecking() bool {
return pr.Status == PullRequestStatusChecking
}
// CanAutoMerge returns true if this pull request can be merged automatically.
func (pr *PullRequest) CanAutoMerge() bool {
return pr.Status == PullRequestStatusMergeable
}
// MergeStyle represents the approach to merge commits into base branch.
type MergeStyle string
const (
MergeStyleRegular MergeStyle = "create_merge_commit"
MergeStyleRebase MergeStyle = "rebase_before_merging"
)
// Merge merges pull request to base repository.
// FIXME: add repoWorkingPull make sure two merges does not happen at same time.
func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository, mergeStyle MergeStyle, commitDescription string) (err error) {
ctx := context.TODO()
defer func() {
go HookQueue.Add(pr.BaseRepo.ID)
go AddTestPullRequestTask(doer, pr.BaseRepo.ID, pr.BaseBranch, false)
}()
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if err = pr.Issue.changeStatus(sess, doer, pr.Issue.Repo, true); err != nil {
return fmt.Errorf("Issue.changeStatus: %v", err)
}
headRepoPath := RepoPath(pr.HeadUserName, pr.HeadRepo.Name)
headGitRepo, err := git.Open(headRepoPath)
if err != nil {
return fmt.Errorf("open repository: %v", err)
}
// Create temporary directory to store temporary copy of the base repository,
// and clean it up when operation finished regardless of succeed or not.
tmpBasePath := filepath.Join(conf.Server.AppDataPath, "tmp", "repos", com.ToStr(time.Now().Nanosecond())+".git")
if err = os.MkdirAll(filepath.Dir(tmpBasePath), os.ModePerm); err != nil {
return err
}
defer func() {
_ = os.RemoveAll(filepath.Dir(tmpBasePath))
}()
// Clone the base repository to the defined temporary directory,
// and checks out to base branch directly.
var stderr string
if _, stderr, err = process.ExecTimeout(5*time.Minute,
fmt.Sprintf("PullRequest.Merge (git clone): %s", tmpBasePath),
"git", "clone", "-b", pr.BaseBranch, baseGitRepo.Path(), tmpBasePath); err != nil {
return fmt.Errorf("git clone: %s", stderr)
}
// Add remote which points to the head repository.
if _, stderr, err = process.ExecDir(-1, tmpBasePath,
fmt.Sprintf("PullRequest.Merge (git remote add): %s", tmpBasePath),
"git", "remote", "add", "head_repo", headRepoPath); err != nil {
return fmt.Errorf("git remote add [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
}
// Fetch information from head repository to the temporary copy.
if _, stderr, err = process.ExecDir(-1, tmpBasePath,
fmt.Sprintf("PullRequest.Merge (git fetch): %s", tmpBasePath),
"git", "fetch", "head_repo"); err != nil {
return fmt.Errorf("git fetch [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
}
remoteHeadBranch := "head_repo/" + pr.HeadBranch
// Check if merge style is allowed, reset to default style if not
if mergeStyle == MergeStyleRebase && !pr.BaseRepo.PullsAllowRebase {
mergeStyle = MergeStyleRegular
}
switch mergeStyle {
case MergeStyleRegular: // Create merge commit
// Merge changes from head branch.
if _, stderr, err = process.ExecDir(-1, tmpBasePath,
fmt.Sprintf("PullRequest.Merge (git merge --no-ff --no-commit): %s", tmpBasePath),
"git", "merge", "--no-ff", "--no-commit", remoteHeadBranch); err != nil {
return fmt.Errorf("git merge --no-ff --no-commit [%s]: %v - %s", tmpBasePath, err, stderr)
}
// Create a merge commit for the base branch.
if _, stderr, err = process.ExecDir(-1, tmpBasePath,
fmt.Sprintf("PullRequest.Merge (git merge): %s", tmpBasePath),
"git", "commit", fmt.Sprintf("--author='%s <%s>'", doer.DisplayName(), doer.Email),
"-m", fmt.Sprintf("Merge branch '%s' of %s/%s into %s", pr.HeadBranch, pr.HeadUserName, pr.HeadRepo.Name, pr.BaseBranch),
"-m", commitDescription); err != nil {
return fmt.Errorf("git commit [%s]: %v - %s", tmpBasePath, err, stderr)
}
case MergeStyleRebase: // Rebase before merging
// Rebase head branch based on base branch, this creates a non-branch commit state.
if _, stderr, err = process.ExecDir(-1, tmpBasePath,
fmt.Sprintf("PullRequest.Merge (git rebase): %s", tmpBasePath),
"git", "rebase", "--quiet", pr.BaseBranch, remoteHeadBranch); err != nil {
return fmt.Errorf("git rebase [%s on %s]: %s", remoteHeadBranch, pr.BaseBranch, stderr)
}
// Name non-branch commit state to a new temporary branch in order to save changes.
tmpBranch := com.ToStr(time.Now().UnixNano(), 10)
if _, stderr, err = process.ExecDir(-1, tmpBasePath,
fmt.Sprintf("PullRequest.Merge (git checkout): %s", tmpBasePath),
"git", "checkout", "-b", tmpBranch); err != nil {
return fmt.Errorf("git checkout '%s': %s", tmpBranch, stderr)
}
// Check out the base branch to be operated on.
if _, stderr, err = process.ExecDir(-1, tmpBasePath,
fmt.Sprintf("PullRequest.Merge (git checkout): %s", tmpBasePath),
"git", "checkout", pr.BaseBranch); err != nil {
return fmt.Errorf("git checkout '%s': %s", pr.BaseBranch, stderr)
}
// Merge changes from temporary branch to the base branch.
if _, stderr, err = process.ExecDir(-1, tmpBasePath,
fmt.Sprintf("PullRequest.Merge (git merge): %s", tmpBasePath),
"git", "merge", tmpBranch); err != nil {
return fmt.Errorf("git merge [%s]: %v - %s", tmpBasePath, err, stderr)
}
default:
return fmt.Errorf("unknown merge style: %s", mergeStyle)
}
// Push changes on base branch to upstream.
if _, stderr, err = process.ExecDir(-1, tmpBasePath,
fmt.Sprintf("PullRequest.Merge (git push): %s", tmpBasePath),
"git", "push", baseGitRepo.Path(), pr.BaseBranch); err != nil {
return fmt.Errorf("git push: %s", stderr)
}
pr.MergedCommitID, err = headGitRepo.BranchCommitID(pr.HeadBranch)
if err != nil {
return fmt.Errorf("get head branch %q commit ID: %v", pr.HeadBranch, err)
}
pr.HasMerged = true
pr.Merged = time.Now()
pr.MergerID = doer.ID
if _, err = sess.ID(pr.ID).AllCols().Update(pr); err != nil {
return fmt.Errorf("update pull request: %v", err)
}
if err = sess.Commit(); err != nil {
return fmt.Errorf("commit: %v", err)
}
if err = Handle.Actions().MergePullRequest(ctx, doer, pr.Issue.Repo.Owner, pr.Issue.Repo, pr.Issue); err != nil {
log.Error("Failed to create action for merge pull request, pull_request_id: %d, error: %v", pr.ID, err)
}
// Reload pull request information.
if err = pr.LoadAttributes(); err != nil {
log.Error("LoadAttributes: %v", err)
return nil
}
if err = PrepareWebhooks(pr.Issue.Repo, HookEventTypePullRequest, &api.PullRequestPayload{
Action: api.HOOK_ISSUE_CLOSED,
Index: pr.Index,
PullRequest: pr.APIFormat(),
Repository: pr.Issue.Repo.APIFormatLegacy(nil),
Sender: doer.APIFormat(),
}); err != nil {
log.Error("PrepareWebhooks: %v", err)
return nil
}
commits, err := headGitRepo.RevList([]string{pr.MergeBase + "..." + pr.MergedCommitID})
if err != nil {
log.Error("Failed to list commits [merge_base: %s, merged_commit_id: %s]: %v", pr.MergeBase, pr.MergedCommitID, err)
return nil
}
// NOTE: It is possible that head branch is not fully sync with base branch
// for merge commits, so we need to get latest head commit and append merge
// commit manually to avoid strange diff commits produced.
mergeCommit, err := baseGitRepo.BranchCommit(pr.BaseBranch)
if err != nil {
log.Error("Failed to get base branch %q commit: %v", pr.BaseBranch, err)
return nil
}
if mergeStyle == MergeStyleRegular {
commits = append([]*git.Commit{mergeCommit}, commits...)
}
pcs, err := CommitsToPushCommits(commits).APIFormat(ctx, Handle.Users(), pr.BaseRepo.RepoPath(), pr.BaseRepo.HTMLURL())
if err != nil {
log.Error("Failed to convert to API payload commits: %v", err)
return nil
}
p := &api.PushPayload{
Ref: git.RefsHeads + pr.BaseBranch,
Before: pr.MergeBase,
After: mergeCommit.ID.String(),
CompareURL: conf.Server.ExternalURL + pr.BaseRepo.ComposeCompareURL(pr.MergeBase, pr.MergedCommitID),
Commits: pcs,
Repo: pr.BaseRepo.APIFormatLegacy(nil),
Pusher: pr.HeadRepo.MustOwner().APIFormat(),
Sender: doer.APIFormat(),
}
if err = PrepareWebhooks(pr.BaseRepo, HookEventTypePush, p); err != nil {
log.Error("Failed to prepare webhooks: %v", err)
return nil
}
return nil
}
// testPatch checks if patch can be merged to base repository without conflict.
// FIXME: make a mechanism to clean up stable local copies.
func (pr *PullRequest) testPatch() (err error) {
if pr.BaseRepo == nil {
pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
if err != nil {
return fmt.Errorf("GetRepositoryByID: %v", err)
}
}
patchPath, err := pr.BaseRepo.PatchPath(pr.Index)
if err != nil {
return fmt.Errorf("BaseRepo.PatchPath: %v", err)
}
// Fast fail if patch does not exist, this assumes data is corrupted.
if !osutil.IsFile(patchPath) {
log.Trace("PullRequest[%d].testPatch: ignored corrupted data", pr.ID)
return nil
}
repoWorkingPool.CheckIn(com.ToStr(pr.BaseRepoID))
defer repoWorkingPool.CheckOut(com.ToStr(pr.BaseRepoID))
log.Trace("PullRequest[%d].testPatch (patchPath): %s", pr.ID, patchPath)
if err := pr.BaseRepo.UpdateLocalCopyBranch(pr.BaseBranch); err != nil {
return fmt.Errorf("UpdateLocalCopy [%d]: %v", pr.BaseRepoID, err)
}
args := []string{"apply", "--check"}
if pr.BaseRepo.PullsIgnoreWhitespace {
args = append(args, "--ignore-whitespace")
}
args = append(args, patchPath)
pr.Status = PullRequestStatusChecking
_, stderr, err := process.ExecDir(-1, pr.BaseRepo.LocalCopyPath(),
fmt.Sprintf("testPatch (git apply --check): %d", pr.BaseRepo.ID),
"git", args...)
if err != nil {
log.Trace("PullRequest[%d].testPatch (apply): has conflict\n%s", pr.ID, stderr)
pr.Status = PullRequestStatusConflict
return nil
}
return nil
}
// NewPullRequest creates new pull request with labels for repository.
func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest, patch []byte) (err error) {
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if err = newIssue(sess, NewIssueOptions{
Repo: repo,
Issue: pull,
LableIDs: labelIDs,
Attachments: uuids,
IsPull: true,
}); err != nil {
return fmt.Errorf("newIssue: %v", err)
}
pr.Index = pull.Index
if err = repo.SavePatch(pr.Index, patch); err != nil {
return fmt.Errorf("SavePatch: %v", err)
}
pr.BaseRepo = repo
if err = pr.testPatch(); err != nil {
return fmt.Errorf("testPatch: %v", err)
}
// No conflict appears after test means mergeable.
if pr.Status == PullRequestStatusChecking {
pr.Status = PullRequestStatusMergeable
}
pr.IssueID = pull.ID
if _, err = sess.Insert(pr); err != nil {
return fmt.Errorf("insert pull repo: %v", err)
}
if err = sess.Commit(); err != nil {
return fmt.Errorf("commit: %v", err)
}
if err = NotifyWatchers(&Action{
ActUserID: pull.Poster.ID,
ActUserName: pull.Poster.Name,
OpType: ActionCreatePullRequest,
Content: fmt.Sprintf("%d|%s", pull.Index, pull.Title),
RepoID: repo.ID,
RepoUserName: repo.Owner.Name,
RepoName: repo.Name,
IsPrivate: repo.IsPrivate,
}); err != nil {
log.Error("NotifyWatchers: %v", err)
}
if err = pull.MailParticipants(); err != nil {
log.Error("MailParticipants: %v", err)
}
pr.Issue = pull
pull.PullRequest = pr
if err = PrepareWebhooks(repo, HookEventTypePullRequest, &api.PullRequestPayload{
Action: api.HOOK_ISSUE_OPENED,
Index: pull.Index,
PullRequest: pr.APIFormat(),
Repository: repo.APIFormatLegacy(nil),
Sender: pull.Poster.APIFormat(),
}); err != nil {
log.Error("PrepareWebhooks: %v", err)
}
return nil
}
// GetUnmergedPullRequest returns a pull request that is open and has not been merged
// by given head/base and repo/branch.
func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch string) (*PullRequest, error) {
pr := new(PullRequest)
has, err := x.Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
headRepoID, headBranch, baseRepoID, baseBranch, false, false).
Join("INNER", "issue", "issue.id=pull_request.issue_id").Get(pr)
if err != nil {
return nil, err
} else if !has {
return nil, ErrPullRequestNotExist{args: map[string]any{
"headRepoID": headRepoID,
"baseRepoID": baseRepoID,
"headBranch": headBranch,
"baseBranch": baseBranch,
}}
}
return pr, nil
}
// GetUnmergedPullRequestsByHeadInfo returns all pull requests that are open and has not been merged
// by given head information (repo and branch).
func GetUnmergedPullRequestsByHeadInfo(repoID int64, branch string) ([]*PullRequest, error) {
prs := make([]*PullRequest, 0, 2)
return prs, x.Where("head_repo_id = ? AND head_branch = ? AND has_merged = ? AND issue.is_closed = ?",
repoID, branch, false, false).
Join("INNER", "issue", "issue.id = pull_request.issue_id").Find(&prs)
}
// GetUnmergedPullRequestsByBaseInfo returns all pull requests that are open and has not been merged
// by given base information (repo and branch).
func GetUnmergedPullRequestsByBaseInfo(repoID int64, branch string) ([]*PullRequest, error) {
prs := make([]*PullRequest, 0, 2)
return prs, x.Where("base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
repoID, branch, false, false).
Join("INNER", "issue", "issue.id=pull_request.issue_id").Find(&prs)
}
var _ errutil.NotFound = (*ErrPullRequestNotExist)(nil)
type ErrPullRequestNotExist struct {
args map[string]any
}
func IsErrPullRequestNotExist(err error) bool {
_, ok := err.(ErrPullRequestNotExist)
return ok
}
func (err ErrPullRequestNotExist) Error() string {
return fmt.Sprintf("pull request does not exist: %v", err.args)
}
func (ErrPullRequestNotExist) NotFound() bool {
return true
}
func getPullRequestByID(e Engine, id int64) (*PullRequest, error) {
pr := new(PullRequest)
has, err := e.ID(id).Get(pr)
if err != nil {
return nil, err
} else if !has {
return nil, ErrPullRequestNotExist{args: map[string]any{"pullRequestID": id}}
}
return pr, pr.loadAttributes(e)
}
// GetPullRequestByID returns a pull request by given ID.
func GetPullRequestByID(id int64) (*PullRequest, error) {
return getPullRequestByID(x, id)
}
func getPullRequestByIssueID(e Engine, issueID int64) (*PullRequest, error) {
pr := &PullRequest{
IssueID: issueID,
}
has, err := e.Get(pr)
if err != nil {
return nil, err
} else if !has {
return nil, ErrPullRequestNotExist{args: map[string]any{"issueID": issueID}}
}
return pr, pr.loadAttributes(e)
}
// GetPullRequestByIssueID returns pull request by given issue ID.
func GetPullRequestByIssueID(issueID int64) (*PullRequest, error) {
return getPullRequestByIssueID(x, issueID)
}
// Update updates all fields of pull request.
func (pr *PullRequest) Update() error {
_, err := x.Id(pr.ID).AllCols().Update(pr)
return err
}
// Update updates specific fields of pull request.
func (pr *PullRequest) UpdateCols(cols ...string) error {
_, err := x.Id(pr.ID).Cols(cols...).Update(pr)
return err
}
// UpdatePatch generates and saves a new patch.
func (pr *PullRequest) UpdatePatch() (err error) {
headGitRepo, err := git.Open(pr.HeadRepo.RepoPath())
if err != nil {
return fmt.Errorf("open repository: %v", err)
}
// Add a temporary remote.
tmpRemote := com.ToStr(time.Now().UnixNano())
baseRepoPath := RepoPath(pr.BaseRepo.MustOwner().Name, pr.BaseRepo.Name)
err = headGitRepo.RemoteAdd(tmpRemote, baseRepoPath, git.RemoteAddOptions{Fetch: true})
if err != nil {
return fmt.Errorf("add remote %q [repo_id: %d]: %v", tmpRemote, pr.HeadRepoID, err)
}
defer func() {
if err := headGitRepo.RemoteRemove(tmpRemote); err != nil {
log.Error("Failed to remove remote %q [repo_id: %d]: %v", tmpRemote, pr.HeadRepoID, err)
}
}()
remoteBranch := "remotes/" + tmpRemote + "/" + pr.BaseBranch
pr.MergeBase, err = headGitRepo.MergeBase(remoteBranch, pr.HeadBranch)
if err != nil {
return fmt.Errorf("get merge base: %v", err)
} else if err = pr.Update(); err != nil {
return fmt.Errorf("update: %v", err)
}
patch, err := headGitRepo.DiffBinary(pr.MergeBase, pr.HeadBranch)
if err != nil {
return fmt.Errorf("get binary patch: %v", err)
}
if err = pr.BaseRepo.SavePatch(pr.Index, patch); err != nil {
return fmt.Errorf("save patch: %v", err)
}
log.Trace("PullRequest[%d].UpdatePatch: patch saved", pr.ID)
return nil
}
// PushToBaseRepo pushes commits from branches of head repository to
// corresponding branches of base repository.
// FIXME: Only push branches that are actually updates?
func (pr *PullRequest) PushToBaseRepo() (err error) {
log.Trace("PushToBaseRepo[%d]: pushing commits to base repo 'refs/pull/%d/head'", pr.BaseRepoID, pr.Index)
headRepoPath := pr.HeadRepo.RepoPath()
headGitRepo, err := git.Open(headRepoPath)
if err != nil {
return fmt.Errorf("open repository: %v", err)
}
tmpRemote := fmt.Sprintf("tmp-pull-%d", pr.ID)
if err = headGitRepo.RemoteAdd(tmpRemote, pr.BaseRepo.RepoPath()); err != nil {
return fmt.Errorf("add remote %q [repo_id: %d]: %v", tmpRemote, pr.HeadRepoID, err)
}
// Make sure to remove the remote even if the push fails
defer func() {
if err := headGitRepo.RemoteRemove(tmpRemote); err != nil {
log.Error("Failed to remove remote %q [repo_id: %d]: %v", tmpRemote, pr.HeadRepoID, err)
}
}()
headRefspec := fmt.Sprintf("refs/pull/%d/head", pr.Index)
headFile := filepath.Join(pr.BaseRepo.RepoPath(), headRefspec)
if osutil.IsExist(headFile) {
err = os.Remove(headFile)
if err != nil {
return fmt.Errorf("remove head file [repo_id: %d]: %v", pr.BaseRepoID, err)
}
}
err = headGitRepo.Push(tmpRemote, fmt.Sprintf("%s:%s", pr.HeadBranch, headRefspec))
if err != nil {
return fmt.Errorf("push: %v", err)
}
return nil
}
// AddToTaskQueue adds itself to pull request test task queue.
func (pr *PullRequest) AddToTaskQueue() {
go PullRequestQueue.AddFunc(pr.ID, func() {
pr.Status = PullRequestStatusChecking
if err := pr.UpdateCols("status"); err != nil {
log.Error("AddToTaskQueue.UpdateCols[%d].(add to queue): %v", pr.ID, err)
}
})
}
type PullRequestList []*PullRequest
func (prs PullRequestList) loadAttributes(e Engine) (err error) {
if len(prs) == 0 {
return nil
}
// Load issues
set := make(map[int64]*Issue)
for i := range prs {
set[prs[i].IssueID] = nil
}
issueIDs := make([]int64, 0, len(prs))
for issueID := range set {
issueIDs = append(issueIDs, issueID)
}
issues := make([]*Issue, 0, len(issueIDs))
if err = e.Where("id > 0").In("id", issueIDs).Find(&issues); err != nil {
return fmt.Errorf("find issues: %v", err)
}
for i := range issues {
set[issues[i].ID] = issues[i]
}
for i := range prs {
prs[i].Issue = set[prs[i].IssueID]
}
// Load attributes
for i := range prs {
if err = prs[i].loadAttributes(e); err != nil {
return fmt.Errorf("loadAttributes [%d]: %v", prs[i].ID, err)
}
}
return nil
}
func (prs PullRequestList) LoadAttributes() error {
return prs.loadAttributes(x)
}
func addHeadRepoTasks(prs []*PullRequest) {
for _, pr := range prs {
if pr.HeadRepo == nil {
log.Trace("addHeadRepoTasks[%d]: missing head repository", pr.ID)
continue
}
log.Trace("addHeadRepoTasks[%d]: composing new test task", pr.ID)
if err := pr.UpdatePatch(); err != nil {
log.Error("UpdatePatch: %v", err)
continue
} else if err := pr.PushToBaseRepo(); err != nil {
log.Error("PushToBaseRepo: %v", err)
continue
}
pr.AddToTaskQueue()
}
}
// AddTestPullRequestTask adds new test tasks by given head/base repository and head/base branch,
// and generate new patch for testing as needed.
func AddTestPullRequestTask(doer *User, repoID int64, branch string, isSync bool) {
log.Trace("AddTestPullRequestTask [head_repo_id: %d, head_branch: %s]: finding pull requests", repoID, branch)
prs, err := GetUnmergedPullRequestsByHeadInfo(repoID, branch)
if err != nil {
log.Error("Find pull requests [head_repo_id: %d, head_branch: %s]: %v", repoID, branch, err)
return
}
if isSync {
if err = PullRequestList(prs).LoadAttributes(); err != nil {
log.Error("PullRequestList.LoadAttributes: %v", err)
}
if err == nil {
for _, pr := range prs {
pr.Issue.PullRequest = pr
if err = pr.Issue.LoadAttributes(); err != nil {
log.Error("LoadAttributes: %v", err)
continue
}
if err = PrepareWebhooks(pr.Issue.Repo, HookEventTypePullRequest, &api.PullRequestPayload{
Action: api.HOOK_ISSUE_SYNCHRONIZED,
Index: pr.Issue.Index,
PullRequest: pr.Issue.PullRequest.APIFormat(),
Repository: pr.Issue.Repo.APIFormatLegacy(nil),
Sender: doer.APIFormat(),
}); err != nil {
log.Error("PrepareWebhooks [pull_id: %v]: %v", pr.ID, err)
continue
}
}
}
}
addHeadRepoTasks(prs)
log.Trace("AddTestPullRequestTask [base_repo_id: %d, base_branch: %s]: finding pull requests", repoID, branch)
prs, err = GetUnmergedPullRequestsByBaseInfo(repoID, branch)
if err != nil {
log.Error("Find pull requests [base_repo_id: %d, base_branch: %s]: %v", repoID, branch, err)
return
}
for _, pr := range prs {
pr.AddToTaskQueue()
}
}
// checkAndUpdateStatus checks if pull request is possible to leaving checking status,
// and set to be either conflict or mergeable.
func (pr *PullRequest) checkAndUpdateStatus() {
// Status is not changed to conflict means mergeable.
if pr.Status == PullRequestStatusChecking {
pr.Status = PullRequestStatusMergeable
}
// Make sure there is no waiting test to process before leaving the checking status.
if !PullRequestQueue.Exist(pr.ID) {
if err := pr.UpdateCols("status"); err != nil {
log.Error("Update[%d]: %v", pr.ID, err)
}
}
}
// TestPullRequests checks and tests untested patches of pull requests.
// TODO: test more pull requests at same time.
func TestPullRequests() {
prs := make([]*PullRequest, 0, 10)
_ = x.Iterate(PullRequest{
Status: PullRequestStatusChecking,
},
func(idx int, bean any) error {
pr := bean.(*PullRequest)
if err := pr.LoadAttributes(); err != nil {
log.Error("LoadAttributes: %v", err)
return nil
}
if err := pr.testPatch(); err != nil {
log.Error("testPatch: %v", err)
return nil
}
prs = append(prs, pr)
return nil
})
// Update pull request status.
for _, pr := range prs {
pr.checkAndUpdateStatus()
}
// Start listening on new test requests.
for prID := range PullRequestQueue.Queue() {
log.Trace("TestPullRequests[%v]: processing test task", prID)
PullRequestQueue.Remove(prID)
pr, err := GetPullRequestByID(com.StrTo(prID).MustInt64())
if err != nil {
log.Error("GetPullRequestByID[%s]: %v", prID, err)
continue
} else if err = pr.testPatch(); err != nil {
log.Error("testPatch[%d]: %v", pr.ID, err)
continue
}
pr.checkAndUpdateStatus()
}
}
func InitTestPullRequests() {
go TestPullRequests()
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/login_sources_test.go | internal/database/login_sources_test.go | // Copyright 2020 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"context"
"testing"
"time"
mockrequire "github.com/derision-test/go-mockgen/v2/testutil/require"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gorm.io/gorm"
"gogs.io/gogs/internal/auth"
"gogs.io/gogs/internal/auth/github"
"gogs.io/gogs/internal/auth/ldap"
"gogs.io/gogs/internal/auth/pam"
"gogs.io/gogs/internal/auth/smtp"
"gogs.io/gogs/internal/errutil"
)
func TestLoginSource_BeforeSave(t *testing.T) {
now := time.Now()
db := &gorm.DB{
Config: &gorm.Config{
SkipDefaultTransaction: true,
NowFunc: func() time.Time {
return now
},
},
}
t.Run("Config has not been set", func(t *testing.T) {
s := &LoginSource{}
err := s.BeforeSave(db)
require.NoError(t, err)
assert.Empty(t, s.Config)
})
t.Run("Config has been set", func(t *testing.T) {
s := &LoginSource{
Provider: pam.NewProvider(&pam.Config{
ServiceName: "pam_service",
}),
}
err := s.BeforeSave(db)
require.NoError(t, err)
assert.Equal(t, `{"ServiceName":"pam_service"}`, s.Config)
})
}
func TestLoginSource_BeforeCreate(t *testing.T) {
now := time.Now()
db := &gorm.DB{
Config: &gorm.Config{
SkipDefaultTransaction: true,
NowFunc: func() time.Time {
return now
},
},
}
t.Run("CreatedUnix has been set", func(t *testing.T) {
s := &LoginSource{
CreatedUnix: 1,
}
_ = s.BeforeCreate(db)
assert.Equal(t, int64(1), s.CreatedUnix)
assert.Equal(t, int64(0), s.UpdatedUnix)
})
t.Run("CreatedUnix has not been set", func(t *testing.T) {
s := &LoginSource{}
_ = s.BeforeCreate(db)
assert.Equal(t, db.NowFunc().Unix(), s.CreatedUnix)
assert.Equal(t, db.NowFunc().Unix(), s.UpdatedUnix)
})
}
func TestLoginSource_BeforeUpdate(t *testing.T) {
now := time.Now()
db := &gorm.DB{
Config: &gorm.Config{
SkipDefaultTransaction: true,
NowFunc: func() time.Time {
return now
},
},
}
s := &LoginSource{}
_ = s.BeforeUpdate(db)
assert.Equal(t, db.NowFunc().Unix(), s.UpdatedUnix)
}
func TestLoginSource_AfterFind(t *testing.T) {
now := time.Now()
db := &gorm.DB{
Config: &gorm.Config{
SkipDefaultTransaction: true,
NowFunc: func() time.Time {
return now
},
},
}
tests := []struct {
name string
authType auth.Type
wantType any
}{
{
name: "LDAP",
authType: auth.LDAP,
wantType: &ldap.Provider{},
},
{
name: "DLDAP",
authType: auth.DLDAP,
wantType: &ldap.Provider{},
},
{
name: "SMTP",
authType: auth.SMTP,
wantType: &smtp.Provider{},
},
{
name: "PAM",
authType: auth.PAM,
wantType: &pam.Provider{},
},
{
name: "GitHub",
authType: auth.GitHub,
wantType: &github.Provider{},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
s := LoginSource{
Type: test.authType,
Config: `{}`,
CreatedUnix: now.Unix(),
UpdatedUnix: now.Unix(),
}
err := s.AfterFind(db)
require.NoError(t, err)
assert.Equal(t, s.CreatedUnix, s.Created.Unix())
assert.Equal(t, s.UpdatedUnix, s.Updated.Unix())
assert.IsType(t, test.wantType, s.Provider)
})
}
}
func TestLoginSources(t *testing.T) {
if testing.Short() {
t.Skip()
}
t.Parallel()
ctx := context.Background()
s := &LoginSourcesStore{
db: newTestDB(t, "LoginSourcesStore"),
}
for _, tc := range []struct {
name string
test func(t *testing.T, ctx context.Context, s *LoginSourcesStore)
}{
{"Create", loginSourcesCreate},
{"Count", loginSourcesCount},
{"DeleteByID", loginSourcesDeleteByID},
{"GetByID", loginSourcesGetByID},
{"List", loginSourcesList},
{"ResetNonDefault", loginSourcesResetNonDefault},
{"Save", loginSourcesSave},
} {
t.Run(tc.name, func(t *testing.T) {
t.Cleanup(func() {
err := clearTables(t, s.db)
require.NoError(t, err)
})
tc.test(t, ctx, s)
})
if t.Failed() {
break
}
}
}
func loginSourcesCreate(t *testing.T, ctx context.Context, s *LoginSourcesStore) {
// Create first login source with name "GitHub"
source, err := s.Create(ctx,
CreateLoginSourceOptions{
Type: auth.GitHub,
Name: "GitHub",
Activated: true,
Default: false,
Config: &github.Config{
APIEndpoint: "https://api.github.com",
},
},
)
require.NoError(t, err)
// Get it back and check the Created field
source, err = s.GetByID(ctx, source.ID)
require.NoError(t, err)
assert.Equal(t, s.db.NowFunc().Format(time.RFC3339), source.Created.UTC().Format(time.RFC3339))
assert.Equal(t, s.db.NowFunc().Format(time.RFC3339), source.Updated.UTC().Format(time.RFC3339))
// Try to create second login source with same name should fail.
_, err = s.Create(ctx, CreateLoginSourceOptions{Name: source.Name})
wantErr := ErrLoginSourceAlreadyExist{args: errutil.Args{"name": source.Name}}
assert.Equal(t, wantErr, err)
}
func setMockLoginSourceFilesStore(t *testing.T, s *LoginSourcesStore, mock loginSourceFilesStore) {
before := s.files
s.files = mock
t.Cleanup(func() {
s.files = before
})
}
func loginSourcesCount(t *testing.T, ctx context.Context, s *LoginSourcesStore) {
// Create two login sources, one in database and one as source file.
_, err := s.Create(ctx,
CreateLoginSourceOptions{
Type: auth.GitHub,
Name: "GitHub",
Activated: true,
Default: false,
Config: &github.Config{
APIEndpoint: "https://api.github.com",
},
},
)
require.NoError(t, err)
mock := NewMockLoginSourceFilesStore()
mock.LenFunc.SetDefaultReturn(2)
setMockLoginSourceFilesStore(t, s, mock)
assert.Equal(t, int64(3), s.Count(ctx))
}
func loginSourcesDeleteByID(t *testing.T, ctx context.Context, s *LoginSourcesStore) {
t.Run("delete but in used", func(t *testing.T) {
source, err := s.Create(ctx,
CreateLoginSourceOptions{
Type: auth.GitHub,
Name: "GitHub",
Activated: true,
Default: false,
Config: &github.Config{
APIEndpoint: "https://api.github.com",
},
},
)
require.NoError(t, err)
// Create a user that uses this login source
_, err = newUsersStore(s.db).Create(ctx, "alice", "",
CreateUserOptions{
LoginSource: source.ID,
},
)
require.NoError(t, err)
// Delete the login source will result in error
err = s.DeleteByID(ctx, source.ID)
wantErr := ErrLoginSourceInUse{args: errutil.Args{"id": source.ID}}
assert.Equal(t, wantErr, err)
})
mock := NewMockLoginSourceFilesStore()
mock.GetByIDFunc.SetDefaultHook(func(id int64) (*LoginSource, error) {
return nil, ErrLoginSourceNotExist{args: errutil.Args{"id": id}}
})
setMockLoginSourceFilesStore(t, s, mock)
// Create a login source with name "GitHub2"
source, err := s.Create(ctx,
CreateLoginSourceOptions{
Type: auth.GitHub,
Name: "GitHub2",
Activated: true,
Default: false,
Config: &github.Config{
APIEndpoint: "https://api.github.com",
},
},
)
require.NoError(t, err)
// Delete a non-existent ID is noop
err = s.DeleteByID(ctx, 9999)
require.NoError(t, err)
// We should be able to get it back
_, err = s.GetByID(ctx, source.ID)
require.NoError(t, err)
// Now delete this login source with ID
err = s.DeleteByID(ctx, source.ID)
require.NoError(t, err)
// We should get token not found error
_, err = s.GetByID(ctx, source.ID)
wantErr := ErrLoginSourceNotExist{args: errutil.Args{"id": source.ID}}
assert.Equal(t, wantErr, err)
}
func loginSourcesGetByID(t *testing.T, ctx context.Context, s *LoginSourcesStore) {
mock := NewMockLoginSourceFilesStore()
mock.GetByIDFunc.SetDefaultHook(func(id int64) (*LoginSource, error) {
if id != 101 {
return nil, ErrLoginSourceNotExist{args: errutil.Args{"id": id}}
}
return &LoginSource{ID: id}, nil
})
setMockLoginSourceFilesStore(t, s, mock)
expConfig := &github.Config{
APIEndpoint: "https://api.github.com",
}
// Create a login source with name "GitHub"
source, err := s.Create(ctx,
CreateLoginSourceOptions{
Type: auth.GitHub,
Name: "GitHub",
Activated: true,
Default: false,
Config: expConfig,
},
)
require.NoError(t, err)
// Get the one in the database and test the read/write hooks
source, err = s.GetByID(ctx, source.ID)
require.NoError(t, err)
assert.Equal(t, expConfig, source.Provider.Config())
// Get the one in source file store
_, err = s.GetByID(ctx, 101)
require.NoError(t, err)
}
func loginSourcesList(t *testing.T, ctx context.Context, s *LoginSourcesStore) {
mock := NewMockLoginSourceFilesStore()
mock.ListFunc.SetDefaultHook(func(opts ListLoginSourceOptions) []*LoginSource {
if opts.OnlyActivated {
return []*LoginSource{
{ID: 1},
}
}
return []*LoginSource{
{ID: 1},
{ID: 2},
}
})
setMockLoginSourceFilesStore(t, s, mock)
// Create two login sources in database, one activated and the other one not
_, err := s.Create(ctx,
CreateLoginSourceOptions{
Type: auth.PAM,
Name: "PAM",
Config: &pam.Config{
ServiceName: "PAM",
},
},
)
require.NoError(t, err)
_, err = s.Create(ctx,
CreateLoginSourceOptions{
Type: auth.GitHub,
Name: "GitHub",
Activated: true,
Config: &github.Config{
APIEndpoint: "https://api.github.com",
},
},
)
require.NoError(t, err)
// List all login sources
sources, err := s.List(ctx, ListLoginSourceOptions{})
require.NoError(t, err)
assert.Equal(t, 4, len(sources), "number of sources")
// Only list activated login sources
sources, err = s.List(ctx, ListLoginSourceOptions{OnlyActivated: true})
require.NoError(t, err)
assert.Equal(t, 2, len(sources), "number of sources")
}
func loginSourcesResetNonDefault(t *testing.T, ctx context.Context, s *LoginSourcesStore) {
mock := NewMockLoginSourceFilesStore()
mock.ListFunc.SetDefaultHook(func(opts ListLoginSourceOptions) []*LoginSource {
mockFile := NewMockLoginSourceFileStore()
mockFile.SetGeneralFunc.SetDefaultHook(func(name, value string) {
assert.Equal(t, "is_default", name)
assert.Equal(t, "false", value)
})
return []*LoginSource{
{
File: mockFile,
},
}
})
setMockLoginSourceFilesStore(t, s, mock)
// Create two login sources both have default on
source1, err := s.Create(ctx,
CreateLoginSourceOptions{
Type: auth.PAM,
Name: "PAM",
Default: true,
Config: &pam.Config{
ServiceName: "PAM",
},
},
)
require.NoError(t, err)
source2, err := s.Create(ctx,
CreateLoginSourceOptions{
Type: auth.GitHub,
Name: "GitHub",
Activated: true,
Default: true,
Config: &github.Config{
APIEndpoint: "https://api.github.com",
},
},
)
require.NoError(t, err)
// Set source 1 as default
err = s.ResetNonDefault(ctx, source1)
require.NoError(t, err)
// Verify the default state
source1, err = s.GetByID(ctx, source1.ID)
require.NoError(t, err)
assert.True(t, source1.IsDefault)
source2, err = s.GetByID(ctx, source2.ID)
require.NoError(t, err)
assert.False(t, source2.IsDefault)
}
func loginSourcesSave(t *testing.T, ctx context.Context, s *LoginSourcesStore) {
t.Run("save to database", func(t *testing.T) {
// Create a login source with name "GitHub"
source, err := s.Create(ctx,
CreateLoginSourceOptions{
Type: auth.GitHub,
Name: "GitHub",
Activated: true,
Default: false,
Config: &github.Config{
APIEndpoint: "https://api.github.com",
},
},
)
require.NoError(t, err)
source.IsActived = false
source.Provider = github.NewProvider(&github.Config{
APIEndpoint: "https://api2.github.com",
})
err = s.Save(ctx, source)
require.NoError(t, err)
source, err = s.GetByID(ctx, source.ID)
require.NoError(t, err)
assert.False(t, source.IsActived)
assert.Equal(t, "https://api2.github.com", source.GitHub().APIEndpoint)
})
t.Run("save to file", func(t *testing.T) {
mockFile := NewMockLoginSourceFileStore()
source := &LoginSource{
Provider: github.NewProvider(&github.Config{
APIEndpoint: "https://api.github.com",
}),
File: mockFile,
}
err := s.Save(ctx, source)
require.NoError(t, err)
mockrequire.Called(t, mockFile.SaveFunc)
})
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/issue_label.go | internal/database/issue_label.go | // Copyright 2016 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"fmt"
"html/template"
"strconv"
"strings"
"xorm.io/xorm"
api "github.com/gogs/go-gogs-client"
"gogs.io/gogs/internal/errutil"
"gogs.io/gogs/internal/lazyregexp"
"gogs.io/gogs/internal/tool"
)
var labelColorPattern = lazyregexp.New("#([a-fA-F0-9]{6})")
// GetLabelTemplateFile loads the label template file by given name,
// then parses and returns a list of name-color pairs.
func GetLabelTemplateFile(name string) ([][2]string, error) {
data, err := getRepoInitFile("label", name)
if err != nil {
return nil, fmt.Errorf("getRepoInitFile: %v", err)
}
lines := strings.Split(string(data), "\n")
list := make([][2]string, 0, len(lines))
for i := 0; i < len(lines); i++ {
line := strings.TrimSpace(lines[i])
if line == "" {
continue
}
fields := strings.SplitN(line, " ", 2)
if len(fields) != 2 {
return nil, fmt.Errorf("line is malformed: %s", line)
}
if !labelColorPattern.MatchString(fields[0]) {
return nil, fmt.Errorf("bad HTML color code in line: %s", line)
}
fields[1] = strings.TrimSpace(fields[1])
list = append(list, [2]string{fields[1], fields[0]})
}
return list, nil
}
// Label represents a label of repository for issues.
type Label struct {
ID int64
RepoID int64 `xorm:"INDEX"`
Name string
Color string `xorm:"VARCHAR(7)"`
NumIssues int
NumClosedIssues int
NumOpenIssues int `xorm:"-" json:"-" gorm:"-"`
IsChecked bool `xorm:"-" json:"-" gorm:"-"`
}
func (l *Label) APIFormat() *api.Label {
return &api.Label{
ID: l.ID,
Name: l.Name,
Color: strings.TrimLeft(l.Color, "#"),
}
}
// CalOpenIssues calculates the open issues of label.
func (l *Label) CalOpenIssues() {
l.NumOpenIssues = l.NumIssues - l.NumClosedIssues
}
// ForegroundColor calculates the text color for labels based
// on their background color.
func (l *Label) ForegroundColor() template.CSS {
if strings.HasPrefix(l.Color, "#") {
if color, err := strconv.ParseUint(l.Color[1:], 16, 64); err == nil {
r := float32(0xFF & (color >> 16))
g := float32(0xFF & (color >> 8))
b := float32(0xFF & color)
luminance := (0.2126*r + 0.7152*g + 0.0722*b) / 255
if luminance < 0.66 {
return template.CSS("#fff")
}
}
}
// default to black
return template.CSS("#000")
}
// NewLabels creates new label(s) for a repository.
func NewLabels(labels ...*Label) error {
_, err := x.Insert(labels)
return err
}
var _ errutil.NotFound = (*ErrLabelNotExist)(nil)
type ErrLabelNotExist struct {
args map[string]any
}
func IsErrLabelNotExist(err error) bool {
_, ok := err.(ErrLabelNotExist)
return ok
}
func (err ErrLabelNotExist) Error() string {
return fmt.Sprintf("label does not exist: %v", err.args)
}
func (ErrLabelNotExist) NotFound() bool {
return true
}
// getLabelOfRepoByName returns a label by Name in given repository.
// If pass repoID as 0, then ORM will ignore limitation of repository
// and can return arbitrary label with any valid ID.
func getLabelOfRepoByName(e Engine, repoID int64, labelName string) (*Label, error) {
if len(labelName) <= 0 {
return nil, ErrLabelNotExist{args: map[string]any{"repoID": repoID}}
}
l := &Label{
Name: labelName,
RepoID: repoID,
}
has, err := e.Get(l)
if err != nil {
return nil, err
} else if !has {
return nil, ErrLabelNotExist{args: map[string]any{"repoID": repoID}}
}
return l, nil
}
// getLabelInRepoByID returns a label by ID in given repository.
// If pass repoID as 0, then ORM will ignore limitation of repository
// and can return arbitrary label with any valid ID.
func getLabelOfRepoByID(e Engine, repoID, labelID int64) (*Label, error) {
if labelID <= 0 {
return nil, ErrLabelNotExist{args: map[string]any{"repoID": repoID, "labelID": labelID}}
}
l := &Label{
ID: labelID,
RepoID: repoID,
}
has, err := e.Get(l)
if err != nil {
return nil, err
} else if !has {
return nil, ErrLabelNotExist{args: map[string]any{"repoID": repoID, "labelID": labelID}}
}
return l, nil
}
// GetLabelByID returns a label by given ID.
func GetLabelByID(id int64) (*Label, error) {
return getLabelOfRepoByID(x, 0, id)
}
// GetLabelOfRepoByID returns a label by ID in given repository.
func GetLabelOfRepoByID(repoID, labelID int64) (*Label, error) {
return getLabelOfRepoByID(x, repoID, labelID)
}
// GetLabelOfRepoByName returns a label by name in given repository.
func GetLabelOfRepoByName(repoID int64, labelName string) (*Label, error) {
return getLabelOfRepoByName(x, repoID, labelName)
}
// GetLabelsInRepoByIDs returns a list of labels by IDs in given repository,
// it silently ignores label IDs that are not belong to the repository.
func GetLabelsInRepoByIDs(repoID int64, labelIDs []int64) ([]*Label, error) {
labels := make([]*Label, 0, len(labelIDs))
return labels, x.Where("repo_id = ?", repoID).In("id", tool.Int64sToStrings(labelIDs)).Asc("name").Find(&labels)
}
// GetLabelsByRepoID returns all labels that belong to given repository by ID.
func GetLabelsByRepoID(repoID int64) ([]*Label, error) {
labels := make([]*Label, 0, 10)
return labels, x.Where("repo_id = ?", repoID).Asc("name").Find(&labels)
}
func getLabelsByIssueID(e Engine, issueID int64) ([]*Label, error) {
issueLabels, err := getIssueLabels(e, issueID)
if err != nil {
return nil, fmt.Errorf("getIssueLabels: %v", err)
} else if len(issueLabels) == 0 {
return []*Label{}, nil
}
labelIDs := make([]int64, len(issueLabels))
for i := range issueLabels {
labelIDs[i] = issueLabels[i].LabelID
}
labels := make([]*Label, 0, len(labelIDs))
return labels, e.Where("id > 0").In("id", tool.Int64sToStrings(labelIDs)).Asc("name").Find(&labels)
}
// GetLabelsByIssueID returns all labels that belong to given issue by ID.
func GetLabelsByIssueID(issueID int64) ([]*Label, error) {
return getLabelsByIssueID(x, issueID)
}
func updateLabel(e Engine, l *Label) error {
_, err := e.ID(l.ID).AllCols().Update(l)
return err
}
// UpdateLabel updates label information.
func UpdateLabel(l *Label) error {
return updateLabel(x, l)
}
// DeleteLabel delete a label of given repository.
func DeleteLabel(repoID, labelID int64) error {
_, err := GetLabelOfRepoByID(repoID, labelID)
if err != nil {
if IsErrLabelNotExist(err) {
return nil
}
return err
}
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if _, err = sess.ID(labelID).Delete(new(Label)); err != nil {
return err
} else if _, err = sess.Where("label_id = ?", labelID).Delete(new(IssueLabel)); err != nil {
return err
}
return sess.Commit()
}
// .___ .____ ___. .__
// | | ______ ________ __ ____ | | _____ \_ |__ ____ | |
// | |/ ___// ___/ | \_/ __ \| | \__ \ | __ \_/ __ \| |
// | |\___ \ \___ \| | /\ ___/| |___ / __ \| \_\ \ ___/| |__
// |___/____ >____ >____/ \___ >_______ (____ /___ /\___ >____/
// \/ \/ \/ \/ \/ \/ \/
// IssueLabel represents an issue-lable relation.
type IssueLabel struct {
ID int64
IssueID int64 `xorm:"UNIQUE(s)"`
LabelID int64 `xorm:"UNIQUE(s)"`
}
func hasIssueLabel(e Engine, issueID, labelID int64) bool {
has, _ := e.Where("issue_id = ? AND label_id = ?", issueID, labelID).Get(new(IssueLabel))
return has
}
// HasIssueLabel returns true if issue has been labeled.
func HasIssueLabel(issueID, labelID int64) bool {
return hasIssueLabel(x, issueID, labelID)
}
func newIssueLabel(e *xorm.Session, issue *Issue, label *Label) (err error) {
if _, err = e.Insert(&IssueLabel{
IssueID: issue.ID,
LabelID: label.ID,
}); err != nil {
return err
}
label.NumIssues++
if issue.IsClosed {
label.NumClosedIssues++
}
if err = updateLabel(e, label); err != nil {
return fmt.Errorf("updateLabel: %v", err)
}
issue.Labels = append(issue.Labels, label)
return nil
}
// NewIssueLabel creates a new issue-label relation.
func NewIssueLabel(issue *Issue, label *Label) (err error) {
if HasIssueLabel(issue.ID, label.ID) {
return nil
}
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if err = newIssueLabel(sess, issue, label); err != nil {
return err
}
return sess.Commit()
}
func newIssueLabels(e *xorm.Session, issue *Issue, labels []*Label) (err error) {
for i := range labels {
if hasIssueLabel(e, issue.ID, labels[i].ID) {
continue
}
if err = newIssueLabel(e, issue, labels[i]); err != nil {
return fmt.Errorf("newIssueLabel: %v", err)
}
}
return nil
}
// NewIssueLabels creates a list of issue-label relations.
func NewIssueLabels(issue *Issue, labels []*Label) (err error) {
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if err = newIssueLabels(sess, issue, labels); err != nil {
return err
}
return sess.Commit()
}
func getIssueLabels(e Engine, issueID int64) ([]*IssueLabel, error) {
issueLabels := make([]*IssueLabel, 0, 10)
return issueLabels, e.Where("issue_id=?", issueID).Asc("label_id").Find(&issueLabels)
}
// GetIssueLabels returns all issue-label relations of given issue by ID.
func GetIssueLabels(issueID int64) ([]*IssueLabel, error) {
return getIssueLabels(x, issueID)
}
func deleteIssueLabel(e *xorm.Session, issue *Issue, label *Label) (err error) {
if _, err = e.Delete(&IssueLabel{
IssueID: issue.ID,
LabelID: label.ID,
}); err != nil {
return err
}
label.NumIssues--
if issue.IsClosed {
label.NumClosedIssues--
}
if err = updateLabel(e, label); err != nil {
return fmt.Errorf("updateLabel: %v", err)
}
for i := range issue.Labels {
if issue.Labels[i].ID == label.ID {
issue.Labels = append(issue.Labels[:i], issue.Labels[i+1:]...)
break
}
}
return nil
}
// DeleteIssueLabel deletes issue-label relation.
func DeleteIssueLabel(issue *Issue, label *Label) (err error) {
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if err = deleteIssueLabel(sess, issue, label); err != nil {
return err
}
return sess.Commit()
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/notices.go | internal/database/notices.go | // Copyright 2023 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"context"
"fmt"
"os"
"strconv"
"time"
"gorm.io/gorm"
log "unknwon.dev/clog/v2"
)
// NoticesStore is the storage layer for system notices.
type NoticesStore struct {
db *gorm.DB
}
func newNoticesStore(db *gorm.DB) *NoticesStore {
return &NoticesStore{db: db}
}
// Create creates a system notice with the given type and description.
func (s *NoticesStore) Create(ctx context.Context, typ NoticeType, desc string) error {
return s.db.WithContext(ctx).Create(
&Notice{
Type: typ,
Description: desc,
},
).Error
}
// DeleteByIDs deletes system notices by given IDs.
func (s *NoticesStore) DeleteByIDs(ctx context.Context, ids ...int64) error {
return s.db.WithContext(ctx).Where("id IN (?)", ids).Delete(&Notice{}).Error
}
// DeleteAll deletes all system notices.
func (s *NoticesStore) DeleteAll(ctx context.Context) error {
return s.db.WithContext(ctx).Where("TRUE").Delete(&Notice{}).Error
}
// List returns a list of system notices. Results are paginated by given page
// and page size, and sorted by primary key (id) in descending order.
func (s *NoticesStore) List(ctx context.Context, page, pageSize int) ([]*Notice, error) {
notices := make([]*Notice, 0, pageSize)
return notices, s.db.WithContext(ctx).
Limit(pageSize).Offset((page - 1) * pageSize).
Order("id DESC").
Find(¬ices).
Error
}
// Count returns the total number of system notices.
func (s *NoticesStore) Count(ctx context.Context) int64 {
var count int64
s.db.WithContext(ctx).Model(&Notice{}).Count(&count)
return count
}
type NoticeType int
const (
NoticeTypeRepository NoticeType = iota + 1
)
// TrStr returns a translation format string.
func (t NoticeType) TrStr() string {
return "admin.notices.type_" + strconv.Itoa(int(t))
}
// Notice represents a system notice for admin.
type Notice struct {
ID int64 `gorm:"primaryKey"`
Type NoticeType
Description string `xorm:"TEXT" gorm:"type:TEXT"`
Created time.Time `xorm:"-" gorm:"-" json:"-"`
CreatedUnix int64
}
// BeforeCreate implements the GORM create hook.
func (n *Notice) BeforeCreate(tx *gorm.DB) error {
if n.CreatedUnix == 0 {
n.CreatedUnix = tx.NowFunc().Unix()
}
return nil
}
// AfterFind implements the GORM query hook.
func (n *Notice) AfterFind(*gorm.DB) error {
n.Created = time.Unix(n.CreatedUnix, 0).Local()
return nil
}
// RemoveAllWithNotice is a helper function to remove all directories in given
// path and creates a system notice in case of an error.
func RemoveAllWithNotice(title, path string) {
if err := os.RemoveAll(path); err != nil {
desc := fmt.Sprintf("%s [%s]: %v", title, path, err)
if err = Handle.Notices().Create(context.Background(), NoticeTypeRepository, desc); err != nil {
log.Error("Failed to create repository notice: %v", err)
}
}
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/repo_branch.go | internal/database/repo_branch.go | // Copyright 2016 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"context"
"fmt"
"strings"
"github.com/gogs/git-module"
"github.com/unknwon/com"
"gogs.io/gogs/internal/errutil"
"gogs.io/gogs/internal/tool"
)
type Branch struct {
RepoPath string
Name string
IsProtected bool
Commit *git.Commit
}
func GetBranchesByPath(path string) ([]*Branch, error) {
gitRepo, err := git.Open(path)
if err != nil {
return nil, fmt.Errorf("open repository: %v", err)
}
names, err := gitRepo.Branches()
if err != nil {
return nil, fmt.Errorf("list branches")
}
branches := make([]*Branch, len(names))
for i := range names {
branches[i] = &Branch{
RepoPath: path,
Name: names[i],
}
}
return branches, nil
}
var _ errutil.NotFound = (*ErrBranchNotExist)(nil)
type ErrBranchNotExist struct {
args map[string]any
}
func IsErrBranchNotExist(err error) bool {
_, ok := err.(ErrBranchNotExist)
return ok
}
func (err ErrBranchNotExist) Error() string {
return fmt.Sprintf("branch does not exist: %v", err.args)
}
func (ErrBranchNotExist) NotFound() bool {
return true
}
func (r *Repository) GetBranch(name string) (*Branch, error) {
if !git.RepoHasBranch(r.RepoPath(), name) {
return nil, ErrBranchNotExist{args: map[string]any{"name": name}}
}
return &Branch{
RepoPath: r.RepoPath(),
Name: name,
}, nil
}
func (r *Repository) GetBranches() ([]*Branch, error) {
return GetBranchesByPath(r.RepoPath())
}
func (br *Branch) GetCommit() (*git.Commit, error) {
gitRepo, err := git.Open(br.RepoPath)
if err != nil {
return nil, fmt.Errorf("open repository: %v", err)
}
return gitRepo.BranchCommit(br.Name)
}
type ProtectBranchWhitelist struct {
ID int64
ProtectBranchID int64
RepoID int64 `xorm:"UNIQUE(protect_branch_whitelist)"`
Name string `xorm:"UNIQUE(protect_branch_whitelist)"`
UserID int64 `xorm:"UNIQUE(protect_branch_whitelist)"`
}
// IsUserInProtectBranchWhitelist returns true if given user is in the whitelist of a branch in a repository.
func IsUserInProtectBranchWhitelist(repoID, userID int64, branch string) bool {
has, err := x.Where("repo_id = ?", repoID).And("user_id = ?", userID).And("name = ?", branch).Get(new(ProtectBranchWhitelist))
return has && err == nil
}
// ProtectBranch contains options of a protected branch.
type ProtectBranch struct {
ID int64
RepoID int64 `xorm:"UNIQUE(protect_branch)"`
Name string `xorm:"UNIQUE(protect_branch)"`
Protected bool
RequirePullRequest bool
EnableWhitelist bool
WhitelistUserIDs string `xorm:"TEXT"`
WhitelistTeamIDs string `xorm:"TEXT"`
}
// GetProtectBranchOfRepoByName returns *ProtectBranch by branch name in given repository.
func GetProtectBranchOfRepoByName(repoID int64, name string) (*ProtectBranch, error) {
protectBranch := &ProtectBranch{
RepoID: repoID,
Name: name,
}
has, err := x.Get(protectBranch)
if err != nil {
return nil, err
} else if !has {
return nil, ErrBranchNotExist{args: map[string]any{"name": name}}
}
return protectBranch, nil
}
// IsBranchOfRepoRequirePullRequest returns true if branch requires pull request in given repository.
func IsBranchOfRepoRequirePullRequest(repoID int64, name string) bool {
protectBranch, err := GetProtectBranchOfRepoByName(repoID, name)
if err != nil {
return false
}
return protectBranch.Protected && protectBranch.RequirePullRequest
}
// UpdateProtectBranch saves branch protection options.
// If ID is 0, it creates a new record. Otherwise, updates existing record.
func UpdateProtectBranch(protectBranch *ProtectBranch) (err error) {
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if protectBranch.ID == 0 {
if _, err = sess.Insert(protectBranch); err != nil {
return fmt.Errorf("insert: %v", err)
}
}
if _, err = sess.ID(protectBranch.ID).AllCols().Update(protectBranch); err != nil {
return fmt.Errorf("update: %v", err)
}
return sess.Commit()
}
// UpdateOrgProtectBranch saves branch protection options of organizational repository.
// If ID is 0, it creates a new record. Otherwise, updates existing record.
// This function also performs check if whitelist user and team's IDs have been changed
// to avoid unnecessary whitelist delete and regenerate.
func UpdateOrgProtectBranch(repo *Repository, protectBranch *ProtectBranch, whitelistUserIDs, whitelistTeamIDs string) (err error) {
if err = repo.GetOwner(); err != nil {
return fmt.Errorf("GetOwner: %v", err)
} else if !repo.Owner.IsOrganization() {
return fmt.Errorf("expect repository owner to be an organization")
}
hasUsersChanged := false
validUserIDs := tool.StringsToInt64s(strings.Split(protectBranch.WhitelistUserIDs, ","))
if protectBranch.WhitelistUserIDs != whitelistUserIDs {
hasUsersChanged = true
userIDs := tool.StringsToInt64s(strings.Split(whitelistUserIDs, ","))
validUserIDs = make([]int64, 0, len(userIDs))
for _, userID := range userIDs {
if !Handle.Permissions().Authorize(context.TODO(), userID, repo.ID, AccessModeWrite,
AccessModeOptions{
OwnerID: repo.OwnerID,
Private: repo.IsPrivate,
},
) {
continue // Drop invalid user ID
}
validUserIDs = append(validUserIDs, userID)
}
protectBranch.WhitelistUserIDs = strings.Join(tool.Int64sToStrings(validUserIDs), ",")
}
hasTeamsChanged := false
validTeamIDs := tool.StringsToInt64s(strings.Split(protectBranch.WhitelistTeamIDs, ","))
if protectBranch.WhitelistTeamIDs != whitelistTeamIDs {
hasTeamsChanged = true
teamIDs := tool.StringsToInt64s(strings.Split(whitelistTeamIDs, ","))
teams, err := GetTeamsHaveAccessToRepo(repo.OwnerID, repo.ID, AccessModeWrite)
if err != nil {
return fmt.Errorf("GetTeamsHaveAccessToRepo [org_id: %d, repo_id: %d]: %v", repo.OwnerID, repo.ID, err)
}
validTeamIDs = make([]int64, 0, len(teams))
for i := range teams {
if teams[i].HasWriteAccess() && com.IsSliceContainsInt64(teamIDs, teams[i].ID) {
validTeamIDs = append(validTeamIDs, teams[i].ID)
}
}
protectBranch.WhitelistTeamIDs = strings.Join(tool.Int64sToStrings(validTeamIDs), ",")
}
// Make sure protectBranch.ID is not 0 for whitelists
if protectBranch.ID == 0 {
if _, err = x.Insert(protectBranch); err != nil {
return fmt.Errorf("insert: %v", err)
}
}
// Merge users and members of teams
var whitelists []*ProtectBranchWhitelist
if hasUsersChanged || hasTeamsChanged {
mergedUserIDs := make(map[int64]bool)
for _, userID := range validUserIDs {
// Empty whitelist users can cause an ID with 0
if userID != 0 {
mergedUserIDs[userID] = true
}
}
for _, teamID := range validTeamIDs {
members, err := GetTeamMembers(teamID)
if err != nil {
return fmt.Errorf("GetTeamMembers [team_id: %d]: %v", teamID, err)
}
for i := range members {
mergedUserIDs[members[i].ID] = true
}
}
whitelists = make([]*ProtectBranchWhitelist, 0, len(mergedUserIDs))
for userID := range mergedUserIDs {
whitelists = append(whitelists, &ProtectBranchWhitelist{
ProtectBranchID: protectBranch.ID,
RepoID: repo.ID,
Name: protectBranch.Name,
UserID: userID,
})
}
}
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if _, err = sess.ID(protectBranch.ID).AllCols().Update(protectBranch); err != nil {
return fmt.Errorf("Update: %v", err)
}
// Refresh whitelists
if hasUsersChanged || hasTeamsChanged {
if _, err = sess.Delete(&ProtectBranchWhitelist{ProtectBranchID: protectBranch.ID}); err != nil {
return fmt.Errorf("delete old protect branch whitelists: %v", err)
} else if _, err = sess.Insert(whitelists); err != nil {
return fmt.Errorf("insert new protect branch whitelists: %v", err)
}
}
return sess.Commit()
}
// GetProtectBranchesByRepoID returns a list of *ProtectBranch in given repository.
func GetProtectBranchesByRepoID(repoID int64) ([]*ProtectBranch, error) {
protectBranches := make([]*ProtectBranch, 0, 2)
return protectBranches, x.Where("repo_id = ? and protected = ?", repoID, true).Asc("name").Find(&protectBranches)
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/repositories.go | internal/database/repositories.go | // Copyright 2020 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"context"
"fmt"
"strings"
"time"
api "github.com/gogs/go-gogs-client"
"github.com/pkg/errors"
"gorm.io/gorm"
"gogs.io/gogs/internal/errutil"
"gogs.io/gogs/internal/repoutil"
)
// BeforeCreate implements the GORM create hook.
func (r *Repository) BeforeCreate(tx *gorm.DB) error {
if r.CreatedUnix == 0 {
r.CreatedUnix = tx.NowFunc().Unix()
}
return nil
}
// BeforeUpdate implements the GORM update hook.
func (r *Repository) BeforeUpdate(tx *gorm.DB) error {
r.UpdatedUnix = tx.NowFunc().Unix()
return nil
}
// AfterFind implements the GORM query hook.
func (r *Repository) AfterFind(_ *gorm.DB) error {
r.Created = time.Unix(r.CreatedUnix, 0).Local()
r.Updated = time.Unix(r.UpdatedUnix, 0).Local()
return nil
}
type RepositoryAPIFormatOptions struct {
Permission *api.Permission
Parent *api.Repository
}
// APIFormat returns the API format of a repository.
func (r *Repository) APIFormat(owner *User, opts ...RepositoryAPIFormatOptions) *api.Repository {
var opt RepositoryAPIFormatOptions
if len(opts) > 0 {
opt = opts[0]
}
cloneLink := repoutil.NewCloneLink(owner.Name, r.Name, false)
return &api.Repository{
ID: r.ID,
Owner: owner.APIFormat(),
Name: r.Name,
FullName: owner.Name + "/" + r.Name,
Description: r.Description,
Private: r.IsPrivate,
Fork: r.IsFork,
Parent: opt.Parent,
Empty: r.IsBare,
Mirror: r.IsMirror,
Size: r.Size,
HTMLURL: repoutil.HTMLURL(owner.Name, r.Name),
SSHURL: cloneLink.SSH,
CloneURL: cloneLink.HTTPS,
Website: r.Website,
Stars: r.NumStars,
Forks: r.NumForks,
Watchers: r.NumWatches,
OpenIssues: r.NumOpenIssues,
DefaultBranch: r.DefaultBranch,
Created: r.Created,
Updated: r.Updated,
Permissions: opt.Permission,
}
}
// RepositoriesStore is the storage layer for repositories.
type RepositoriesStore struct {
db *gorm.DB
}
func newReposStore(db *gorm.DB) *RepositoriesStore {
return &RepositoriesStore{db: db}
}
type ErrRepoAlreadyExist struct {
args errutil.Args
}
func IsErrRepoAlreadyExist(err error) bool {
_, ok := err.(ErrRepoAlreadyExist)
return ok
}
func (err ErrRepoAlreadyExist) Error() string {
return fmt.Sprintf("repository already exists: %v", err.args)
}
type CreateRepoOptions struct {
Name string
Description string
DefaultBranch string
Private bool
Mirror bool
EnableWiki bool
EnableIssues bool
EnablePulls bool
Fork bool
ForkID int64
}
// Create creates a new repository record in the database. It returns
// ErrNameNotAllowed when the repository name is not allowed, or
// ErrRepoAlreadyExist when a repository with same name already exists for the
// owner.
func (s *RepositoriesStore) Create(ctx context.Context, ownerID int64, opts CreateRepoOptions) (*Repository, error) {
err := isRepoNameAllowed(opts.Name)
if err != nil {
return nil, err
}
_, err = s.GetByName(ctx, ownerID, opts.Name)
if err == nil {
return nil, ErrRepoAlreadyExist{
args: errutil.Args{
"ownerID": ownerID,
"name": opts.Name,
},
}
} else if !IsErrRepoNotExist(err) {
return nil, err
}
repo := &Repository{
OwnerID: ownerID,
LowerName: strings.ToLower(opts.Name),
Name: opts.Name,
Description: opts.Description,
DefaultBranch: opts.DefaultBranch,
IsPrivate: opts.Private,
IsMirror: opts.Mirror,
EnableWiki: opts.EnableWiki,
EnableIssues: opts.EnableIssues,
EnablePulls: opts.EnablePulls,
IsFork: opts.Fork,
ForkID: opts.ForkID,
}
return repo, s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
err = tx.Create(repo).Error
if err != nil {
return errors.Wrap(err, "create")
}
err = newReposStore(tx).Watch(ctx, ownerID, repo.ID)
if err != nil {
return errors.Wrap(err, "watch")
}
return nil
})
}
// GetByCollaboratorID returns a list of repositories that the given
// collaborator has access to. Results are limited to the given limit and sorted
// by the given order (e.g. "updated_unix DESC"). Repositories that are owned
// directly by the given collaborator are not included.
func (s *RepositoriesStore) GetByCollaboratorID(ctx context.Context, collaboratorID int64, limit int, orderBy string) ([]*Repository, error) {
/*
Equivalent SQL for PostgreSQL:
SELECT * FROM repository
JOIN access ON access.repo_id = repository.id AND access.user_id = @collaboratorID
WHERE access.mode >= @accessModeRead
ORDER BY @orderBy
LIMIT @limit
*/
var repos []*Repository
return repos, s.db.WithContext(ctx).
Joins("JOIN access ON access.repo_id = repository.id AND access.user_id = ?", collaboratorID).
Where("access.mode >= ?", AccessModeRead).
Order(orderBy).
Limit(limit).
Find(&repos).
Error
}
// GetByCollaboratorIDWithAccessMode returns a list of repositories and
// corresponding access mode that the given collaborator has access to.
// Repositories that are owned directly by the given collaborator are not
// included.
func (s *RepositoriesStore) GetByCollaboratorIDWithAccessMode(ctx context.Context, collaboratorID int64) (map[*Repository]AccessMode, error) {
/*
Equivalent SQL for PostgreSQL:
SELECT
repository.*,
access.mode
FROM repository
JOIN access ON access.repo_id = repository.id AND access.user_id = @collaboratorID
WHERE access.mode >= @accessModeRead
*/
var reposWithAccessMode []*struct {
*Repository
Mode AccessMode
}
err := s.db.WithContext(ctx).
Select("repository.*", "access.mode").
Table("repository").
Joins("JOIN access ON access.repo_id = repository.id AND access.user_id = ?", collaboratorID).
Where("access.mode >= ?", AccessModeRead).
Find(&reposWithAccessMode).
Error
if err != nil {
return nil, err
}
repos := make(map[*Repository]AccessMode, len(reposWithAccessMode))
for _, repoWithAccessMode := range reposWithAccessMode {
repos[repoWithAccessMode.Repository] = repoWithAccessMode.Mode
}
return repos, nil
}
var _ errutil.NotFound = (*ErrRepoNotExist)(nil)
type ErrRepoNotExist struct {
args errutil.Args
}
func IsErrRepoNotExist(err error) bool {
_, ok := err.(ErrRepoNotExist)
return ok
}
func (err ErrRepoNotExist) Error() string {
return fmt.Sprintf("repository does not exist: %v", err.args)
}
func (ErrRepoNotExist) NotFound() bool {
return true
}
// GetByID returns the repository with given ID. It returns ErrRepoNotExist when
// not found.
func (s *RepositoriesStore) GetByID(ctx context.Context, id int64) (*Repository, error) {
repo := new(Repository)
err := s.db.WithContext(ctx).Where("id = ?", id).First(repo).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrRepoNotExist{errutil.Args{"repoID": id}}
}
return nil, err
}
return repo, nil
}
// GetByName returns the repository with given owner and name. It returns
// ErrRepoNotExist when not found.
func (s *RepositoriesStore) GetByName(ctx context.Context, ownerID int64, name string) (*Repository, error) {
repo := new(Repository)
err := s.db.WithContext(ctx).
Where("owner_id = ? AND lower_name = ?", ownerID, strings.ToLower(name)).
First(repo).
Error
if err != nil {
if err == gorm.ErrRecordNotFound {
return nil, ErrRepoNotExist{
args: errutil.Args{
"ownerID": ownerID,
"name": name,
},
}
}
return nil, err
}
return repo, nil
}
func (s *RepositoriesStore) recountStars(tx *gorm.DB, userID, repoID int64) error {
/*
Equivalent SQL for PostgreSQL:
UPDATE repository
SET num_stars = (
SELECT COUNT(*) FROM star WHERE repo_id = @repoID
)
WHERE id = @repoID
*/
err := tx.Model(&Repository{}).
Where("id = ?", repoID).
Update(
"num_stars",
tx.Model(&Star{}).Select("COUNT(*)").Where("repo_id = ?", repoID),
).
Error
if err != nil {
return errors.Wrap(err, `update "repository.num_stars"`)
}
/*
Equivalent SQL for PostgreSQL:
UPDATE "user"
SET num_stars = (
SELECT COUNT(*) FROM star WHERE uid = @userID
)
WHERE id = @userID
*/
err = tx.Model(&User{}).
Where("id = ?", userID).
Update(
"num_stars",
tx.Model(&Star{}).Select("COUNT(*)").Where("uid = ?", userID),
).
Error
if err != nil {
return errors.Wrap(err, `update "user.num_stars"`)
}
return nil
}
// Star marks the user to star the repository.
func (s *RepositoriesStore) Star(ctx context.Context, userID, repoID int64) error {
return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
star := &Star{
UserID: userID,
RepoID: repoID,
}
result := tx.FirstOrCreate(star, star)
if result.Error != nil {
return errors.Wrap(result.Error, "upsert")
} else if result.RowsAffected <= 0 {
return nil // Relation already exists
}
return s.recountStars(tx, userID, repoID)
})
}
// Touch updates the updated time to the current time and removes the bare state
// of the given repository.
func (s *RepositoriesStore) Touch(ctx context.Context, id int64) error {
return s.db.WithContext(ctx).
Model(new(Repository)).
Where("id = ?", id).
Updates(map[string]any{
"is_bare": false,
"updated_unix": s.db.NowFunc().Unix(),
}).
Error
}
// ListWatches returns all watches of the given repository.
func (s *RepositoriesStore) ListWatches(ctx context.Context, repoID int64) ([]*Watch, error) {
var watches []*Watch
return watches, s.db.WithContext(ctx).Where("repo_id = ?", repoID).Find(&watches).Error
}
func (s *RepositoriesStore) recountWatches(tx *gorm.DB, repoID int64) error {
/*
Equivalent SQL for PostgreSQL:
UPDATE repository
SET num_watches = (
SELECT COUNT(*) FROM watch WHERE repo_id = @repoID
)
WHERE id = @repoID
*/
return tx.Model(&Repository{}).
Where("id = ?", repoID).
Update(
"num_watches",
tx.Model(&Watch{}).Select("COUNT(*)").Where("repo_id = ?", repoID),
).
Error
}
// Watch marks the user to watch the repository.
func (s *RepositoriesStore) Watch(ctx context.Context, userID, repoID int64) error {
return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
w := &Watch{
UserID: userID,
RepoID: repoID,
}
result := tx.FirstOrCreate(w, w)
if result.Error != nil {
return errors.Wrap(result.Error, "upsert")
} else if result.RowsAffected <= 0 {
return nil // Relation already exists
}
return s.recountWatches(tx, repoID)
})
}
// HasForkedBy returns true if the given repository has forked by the given user.
func (s *RepositoriesStore) HasForkedBy(ctx context.Context, repoID, userID int64) bool {
var count int64
s.db.WithContext(ctx).Model(new(Repository)).Where("owner_id = ? AND fork_id = ?", userID, repoID).Count(&count)
return count > 0
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/users.go | internal/database/users.go | // Copyright 2020 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"context"
"database/sql"
"fmt"
"os"
"strings"
"time"
"unicode/utf8"
"github.com/go-macaron/binding"
api "github.com/gogs/go-gogs-client"
"github.com/pkg/errors"
"gorm.io/gorm"
log "unknwon.dev/clog/v2"
"gogs.io/gogs/internal/auth"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/cryptoutil"
"gogs.io/gogs/internal/dbutil"
"gogs.io/gogs/internal/errutil"
"gogs.io/gogs/internal/markup"
"gogs.io/gogs/internal/osutil"
"gogs.io/gogs/internal/repoutil"
"gogs.io/gogs/internal/strutil"
"gogs.io/gogs/internal/tool"
"gogs.io/gogs/internal/userutil"
)
// UsersStore is the storage layer for users.
type UsersStore struct {
db *gorm.DB
}
func newUsersStore(db *gorm.DB) *UsersStore {
return &UsersStore{db: db}
}
type ErrLoginSourceMismatch struct {
args errutil.Args
}
// IsErrLoginSourceMismatch returns true if the underlying error has the type
// ErrLoginSourceMismatch.
func IsErrLoginSourceMismatch(err error) bool {
return errors.As(err, &ErrLoginSourceMismatch{})
}
func (err ErrLoginSourceMismatch) Error() string {
return fmt.Sprintf("login source mismatch: %v", err.args)
}
// Authenticate validates username and password via given login source ID. It
// returns ErrUserNotExist when the user was not found.
//
// When the "loginSourceID" is negative, it aborts the process and returns
// ErrUserNotExist if the user was not found in the database.
//
// When the "loginSourceID" is non-negative, it returns ErrLoginSourceMismatch
// if the user has different login source ID than the "loginSourceID".
//
// When the "loginSourceID" is positive, it tries to authenticate via given
// login source and creates a new user when not yet exists in the database.
func (s *UsersStore) Authenticate(ctx context.Context, login, password string, loginSourceID int64) (*User, error) {
login = strings.ToLower(login)
query := s.db.WithContext(ctx)
if strings.Contains(login, "@") {
query = query.Where("email = ?", login)
} else {
query = query.Where("lower_name = ?", login)
}
user := new(User)
err := query.First(user).Error
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return nil, errors.Wrap(err, "get user")
}
var authSourceID int64 // The login source ID will be used to authenticate the user
createNewUser := false // Whether to create a new user after successful authentication
// User found in the database
if err == nil {
// Note: This check is unnecessary but to reduce user confusion at login page
// and make it more consistent from user's perspective.
if loginSourceID >= 0 && user.LoginSource != loginSourceID {
return nil, ErrLoginSourceMismatch{args: errutil.Args{"expect": loginSourceID, "actual": user.LoginSource}}
}
// Validate password hash fetched from database for local accounts.
if user.IsLocal() {
if userutil.ValidatePassword(user.Password, user.Salt, password) {
return user, nil
}
return nil, auth.ErrBadCredentials{Args: map[string]any{"login": login, "userID": user.ID}}
}
authSourceID = user.LoginSource
} else {
// Non-local login source is always greater than 0.
if loginSourceID <= 0 {
return nil, auth.ErrBadCredentials{Args: map[string]any{"login": login}}
}
authSourceID = loginSourceID
createNewUser = true
}
source, err := newLoginSourcesStore(s.db, loadedLoginSourceFilesStore).GetByID(ctx, authSourceID)
if err != nil {
return nil, errors.Wrap(err, "get login source")
}
if !source.IsActived {
return nil, errors.Errorf("login source %d is not activated", source.ID)
}
extAccount, err := source.Provider.Authenticate(login, password)
if err != nil {
return nil, err
}
if !createNewUser {
return user, nil
}
// Validate username make sure it satisfies requirement.
if binding.AlphaDashDotPattern.MatchString(extAccount.Name) {
return nil, fmt.Errorf("invalid pattern for attribute 'username' [%s]: must be valid alpha or numeric or dash(-_) or dot characters", extAccount.Name)
}
return s.Create(ctx, extAccount.Name, extAccount.Email,
CreateUserOptions{
FullName: extAccount.FullName,
LoginSource: authSourceID,
LoginName: extAccount.Login,
Location: extAccount.Location,
Website: extAccount.Website,
Activated: true,
Admin: extAccount.Admin,
},
)
}
// ChangeUsername changes the username of the given user and updates all
// references to the old username. It returns ErrNameNotAllowed if the given
// name or pattern of the name is not allowed as a username, or
// ErrUserAlreadyExist when another user with same name already exists.
func (s *UsersStore) ChangeUsername(ctx context.Context, userID int64, newUsername string) error {
err := isUsernameAllowed(newUsername)
if err != nil {
return err
}
if s.IsUsernameUsed(ctx, newUsername, userID) {
return ErrUserAlreadyExist{
args: errutil.Args{
"name": newUsername,
},
}
}
user, err := s.GetByID(ctx, userID)
if err != nil {
return errors.Wrap(err, "get user")
}
return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
err := tx.Model(&User{}).
Where("id = ?", user.ID).
Updates(map[string]any{
"lower_name": strings.ToLower(newUsername),
"name": newUsername,
"updated_unix": tx.NowFunc().Unix(),
}).Error
if err != nil {
return errors.Wrap(err, "update user name")
}
// Stop here if it's just a case-change of the username
if strings.EqualFold(user.Name, newUsername) {
return nil
}
// Update all references to the user name in pull requests
err = tx.Model(&PullRequest{}).
Where("head_user_name = ?", user.LowerName).
Update("head_user_name", strings.ToLower(newUsername)).
Error
if err != nil {
return errors.Wrap(err, `update "pull_request.head_user_name"`)
}
// Delete local copies of repositories and their wikis that are owned by the user
rows, err := tx.Model(&Repository{}).Where("owner_id = ?", user.ID).Rows()
if err != nil {
return errors.Wrap(err, "iterate repositories")
}
defer func() { _ = rows.Close() }()
for rows.Next() {
var repo struct {
ID int64
}
err = tx.ScanRows(rows, &repo)
if err != nil {
return errors.Wrap(err, "scan rows")
}
deleteRepoLocalCopy(repo.ID)
RemoveAllWithNotice(fmt.Sprintf("Delete repository %d wiki local copy", repo.ID), repoutil.RepositoryLocalWikiPath(repo.ID))
}
if err = rows.Err(); err != nil {
return errors.Wrap(err, "check rows.Err")
}
// Rename user directory if exists
userPath := repoutil.UserPath(user.Name)
if osutil.IsExist(userPath) {
newUserPath := repoutil.UserPath(newUsername)
err = os.Rename(userPath, newUserPath)
if err != nil {
return errors.Wrap(err, "rename user directory")
}
}
return nil
})
}
// Count returns the total number of users.
func (s *UsersStore) Count(ctx context.Context) int64 {
var count int64
s.db.WithContext(ctx).Model(&User{}).Where("type = ?", UserTypeIndividual).Count(&count)
return count
}
type CreateUserOptions struct {
FullName string
Password string
LoginSource int64
LoginName string
Location string
Website string
Activated bool
Admin bool
}
type ErrUserAlreadyExist struct {
args errutil.Args
}
// IsErrUserAlreadyExist returns true if the underlying error has the type
// ErrUserAlreadyExist.
func IsErrUserAlreadyExist(err error) bool {
return errors.As(err, &ErrUserAlreadyExist{})
}
func (err ErrUserAlreadyExist) Error() string {
return fmt.Sprintf("user already exists: %v", err.args)
}
type ErrEmailAlreadyUsed struct {
args errutil.Args
}
// IsErrEmailAlreadyUsed returns true if the underlying error has the type
// ErrEmailAlreadyUsed.
func IsErrEmailAlreadyUsed(err error) bool {
return errors.As(err, &ErrEmailAlreadyUsed{})
}
func (err ErrEmailAlreadyUsed) Email() string {
email, ok := err.args["email"].(string)
if ok {
return email
}
return "<email not found>"
}
func (err ErrEmailAlreadyUsed) Error() string {
return fmt.Sprintf("email has been used: %v", err.args)
}
// Create creates a new user and persists to database. It returns
// ErrNameNotAllowed if the given name or pattern of the name is not allowed as
// a username, or ErrUserAlreadyExist when a user with same name already exists,
// or ErrEmailAlreadyUsed if the email has been verified by another user.
func (s *UsersStore) Create(ctx context.Context, username, email string, opts CreateUserOptions) (*User, error) {
err := isUsernameAllowed(username)
if err != nil {
return nil, err
}
if s.IsUsernameUsed(ctx, username, 0) {
return nil, ErrUserAlreadyExist{
args: errutil.Args{
"name": username,
},
}
}
email = strings.ToLower(strings.TrimSpace(email))
_, err = s.GetByEmail(ctx, email)
if err == nil {
return nil, ErrEmailAlreadyUsed{
args: errutil.Args{
"email": email,
},
}
} else if !IsErrUserNotExist(err) {
return nil, err
}
user := &User{
LowerName: strings.ToLower(username),
Name: username,
FullName: opts.FullName,
Email: email,
Password: opts.Password,
LoginSource: opts.LoginSource,
LoginName: opts.LoginName,
Location: opts.Location,
Website: opts.Website,
MaxRepoCreation: -1,
IsActive: opts.Activated,
IsAdmin: opts.Admin,
Avatar: cryptoutil.MD5(email), // Gravatar URL uses the MD5 hash of the email, see https://en.gravatar.com/site/implement/hash/
AvatarEmail: email,
}
user.Rands, err = userutil.RandomSalt()
if err != nil {
return nil, err
}
user.Salt, err = userutil.RandomSalt()
if err != nil {
return nil, err
}
user.Password = userutil.EncodePassword(user.Password, user.Salt)
return user, s.db.WithContext(ctx).Create(user).Error
}
// DeleteCustomAvatar deletes the current user custom avatar and falls back to
// use look up avatar by email.
func (s *UsersStore) DeleteCustomAvatar(ctx context.Context, userID int64) error {
_ = os.Remove(userutil.CustomAvatarPath(userID))
return s.db.WithContext(ctx).
Model(&User{}).
Where("id = ?", userID).
Updates(map[string]any{
"use_custom_avatar": false,
"updated_unix": s.db.NowFunc().Unix(),
}).
Error
}
type ErrUserOwnRepos struct {
args errutil.Args
}
// IsErrUserOwnRepos returns true if the underlying error has the type
// ErrUserOwnRepos.
func IsErrUserOwnRepos(err error) bool {
return errors.As(err, &ErrUserOwnRepos{})
}
func (err ErrUserOwnRepos) Error() string {
return fmt.Sprintf("user still has repository ownership: %v", err.args)
}
type ErrUserHasOrgs struct {
args errutil.Args
}
// IsErrUserHasOrgs returns true if the underlying error has the type
// ErrUserHasOrgs.
func IsErrUserHasOrgs(err error) bool {
return errors.As(err, &ErrUserHasOrgs{})
}
func (err ErrUserHasOrgs) Error() string {
return fmt.Sprintf("user still has organization membership: %v", err.args)
}
// DeleteByID deletes the given user and all their resources. It returns
// ErrUserOwnRepos when the user still has repository ownership, or returns
// ErrUserHasOrgs when the user still has organization membership. It is more
// performant to skip rewriting the "authorized_keys" file for individual
// deletion in a batch operation.
func (s *UsersStore) DeleteByID(ctx context.Context, userID int64, skipRewriteAuthorizedKeys bool) error {
user, err := s.GetByID(ctx, userID)
if err != nil {
if IsErrUserNotExist(err) {
return nil
}
return errors.Wrap(err, "get user")
}
// Double-check the user is not a direct owner of any repository and not a
// member of any organization.
var count int64
err = s.db.WithContext(ctx).Model(&Repository{}).Where("owner_id = ?", userID).Count(&count).Error
if err != nil {
return errors.Wrap(err, "count repositories")
} else if count > 0 {
return ErrUserOwnRepos{args: errutil.Args{"userID": userID}}
}
err = s.db.WithContext(ctx).Model(&OrgUser{}).Where("uid = ?", userID).Count(&count).Error
if err != nil {
return errors.Wrap(err, "count organization membership")
} else if count > 0 {
return ErrUserHasOrgs{args: errutil.Args{"userID": userID}}
}
needsRewriteAuthorizedKeys := false
err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
/*
Equivalent SQL for PostgreSQL:
UPDATE repository
SET num_watches = num_watches - 1
WHERE id IN (
SELECT repo_id FROM watch WHERE user_id = @userID
)
*/
err = tx.Table("repository").
Where("id IN (?)", tx.
Select("repo_id").
Table("watch").
Where("user_id = ?", userID),
).
UpdateColumn("num_watches", gorm.Expr("num_watches - 1")).
Error
if err != nil {
return errors.Wrap(err, `decrease "repository.num_watches"`)
}
/*
Equivalent SQL for PostgreSQL:
UPDATE repository
SET num_stars = num_stars - 1
WHERE id IN (
SELECT repo_id FROM star WHERE uid = @userID
)
*/
err = tx.Table("repository").
Where("id IN (?)", tx.
Select("repo_id").
Table("star").
Where("uid = ?", userID),
).
UpdateColumn("num_stars", gorm.Expr("num_stars - 1")).
Error
if err != nil {
return errors.Wrap(err, `decrease "repository.num_stars"`)
}
/*
Equivalent SQL for PostgreSQL:
UPDATE user
SET num_followers = num_followers - 1
WHERE id IN (
SELECT follow_id FROM follow WHERE user_id = @userID
)
*/
err = tx.Table("user").
Where("id IN (?)", tx.
Select("follow_id").
Table("follow").
Where("user_id = ?", userID),
).
UpdateColumn("num_followers", gorm.Expr("num_followers - 1")).
Error
if err != nil {
return errors.Wrap(err, `decrease "user.num_followers"`)
}
/*
Equivalent SQL for PostgreSQL:
UPDATE user
SET num_following = num_following - 1
WHERE id IN (
SELECT user_id FROM follow WHERE follow_id = @userID
)
*/
err = tx.Table("user").
Where("id IN (?)", tx.
Select("user_id").
Table("follow").
Where("follow_id = ?", userID),
).
UpdateColumn("num_following", gorm.Expr("num_following - 1")).
Error
if err != nil {
return errors.Wrap(err, `decrease "user.num_following"`)
}
if !skipRewriteAuthorizedKeys {
// We need to rewrite "authorized_keys" file if the user owns any public keys.
needsRewriteAuthorizedKeys = tx.Where("owner_id = ?", userID).First(&PublicKey{}).Error != gorm.ErrRecordNotFound
}
err = tx.Model(&Issue{}).Where("assignee_id = ?", userID).Update("assignee_id", 0).Error
if err != nil {
return errors.Wrap(err, "clear assignees")
}
for _, t := range []struct {
table any
where string
}{
{&Watch{}, "user_id = @userID"},
{&Star{}, "uid = @userID"},
{&Follow{}, "user_id = @userID OR follow_id = @userID"},
{&PublicKey{}, "owner_id = @userID"},
{&AccessToken{}, "uid = @userID"},
{&Collaboration{}, "user_id = @userID"},
{&Access{}, "user_id = @userID"},
{&Action{}, "user_id = @userID"},
{&IssueUser{}, "uid = @userID"},
{&EmailAddress{}, "uid = @userID"},
{&User{}, "id = @userID"},
} {
err = tx.Where(t.where, sql.Named("userID", userID)).Delete(t.table).Error
if err != nil {
return errors.Wrapf(err, "clean up table %T", t.table)
}
}
return nil
})
if err != nil {
return err
}
_ = os.RemoveAll(repoutil.UserPath(user.Name))
_ = os.Remove(userutil.CustomAvatarPath(userID))
if needsRewriteAuthorizedKeys {
err = newPublicKeysStore(s.db).RewriteAuthorizedKeys()
if err != nil {
return errors.Wrap(err, `rewrite "authorized_keys" file`)
}
}
return nil
}
// DeleteInactivated deletes all inactivated users.
//
// NOTE: We do not take context.Context here because this operation in practice
// could much longer than the general request timeout (e.g. one minute).
func (s *UsersStore) DeleteInactivated() error {
var userIDs []int64
err := s.db.Model(&User{}).Where("is_active = ?", false).Pluck("id", &userIDs).Error
if err != nil {
return errors.Wrap(err, "get inactivated user IDs")
}
for _, userID := range userIDs {
err = s.DeleteByID(context.Background(), userID, true)
if err != nil {
// Skip users that may had set to inactivated by admins.
if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
continue
}
return errors.Wrapf(err, "delete user with ID %d", userID)
}
}
err = newPublicKeysStore(s.db).RewriteAuthorizedKeys()
if err != nil {
return errors.Wrap(err, `rewrite "authorized_keys" file`)
}
return nil
}
func (*UsersStore) recountFollows(tx *gorm.DB, userID, followID int64) error {
/*
Equivalent SQL for PostgreSQL:
UPDATE "user"
SET num_followers = (
SELECT COUNT(*) FROM follow WHERE follow_id = @followID
)
WHERE id = @followID
*/
err := tx.Model(&User{}).
Where("id = ?", followID).
Update(
"num_followers",
tx.Model(&Follow{}).Select("COUNT(*)").Where("follow_id = ?", followID),
).
Error
if err != nil {
return errors.Wrap(err, `update "user.num_followers"`)
}
/*
Equivalent SQL for PostgreSQL:
UPDATE "user"
SET num_following = (
SELECT COUNT(*) FROM follow WHERE user_id = @userID
)
WHERE id = @userID
*/
err = tx.Model(&User{}).
Where("id = ?", userID).
Update(
"num_following",
tx.Model(&Follow{}).Select("COUNT(*)").Where("user_id = ?", userID),
).
Error
if err != nil {
return errors.Wrap(err, `update "user.num_following"`)
}
return nil
}
// Follow marks the user to follow the other user.
func (s *UsersStore) Follow(ctx context.Context, userID, followID int64) error {
if userID == followID {
return nil
}
return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
f := &Follow{
UserID: userID,
FollowID: followID,
}
result := tx.FirstOrCreate(f, f)
if result.Error != nil {
return errors.Wrap(result.Error, "upsert")
} else if result.RowsAffected <= 0 {
return nil // Relation already exists
}
return s.recountFollows(tx, userID, followID)
})
}
// Unfollow removes the mark the user to follow the other user.
func (s *UsersStore) Unfollow(ctx context.Context, userID, followID int64) error {
if userID == followID {
return nil
}
return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
err := tx.Where("user_id = ? AND follow_id = ?", userID, followID).Delete(&Follow{}).Error
if err != nil {
return errors.Wrap(err, "delete")
}
return s.recountFollows(tx, userID, followID)
})
}
// IsFollowing returns true if the user is following the other user.
func (s *UsersStore) IsFollowing(ctx context.Context, userID, followID int64) bool {
return s.db.WithContext(ctx).Where("user_id = ? AND follow_id = ?", userID, followID).First(&Follow{}).Error == nil
}
var _ errutil.NotFound = (*ErrUserNotExist)(nil)
type ErrUserNotExist struct {
args errutil.Args
}
// IsErrUserNotExist returns true if the underlying error has the type
// ErrUserNotExist.
func IsErrUserNotExist(err error) bool {
_, ok := errors.Cause(err).(ErrUserNotExist)
return ok
}
func (err ErrUserNotExist) Error() string {
return fmt.Sprintf("user does not exist: %v", err.args)
}
func (ErrUserNotExist) NotFound() bool {
return true
}
// GetByEmail returns the user (not organization) with given email. It ignores
// records with unverified emails and returns ErrUserNotExist when not found.
func (s *UsersStore) GetByEmail(ctx context.Context, email string) (*User, error) {
if email == "" {
return nil, ErrUserNotExist{args: errutil.Args{"email": email}}
}
email = strings.ToLower(email)
/*
Equivalent SQL for PostgreSQL:
SELECT * FROM "user"
LEFT JOIN email_address ON email_address.uid = "user".id
WHERE
"user".type = @userType
AND (
"user".email = @email AND "user".is_active = TRUE
OR email_address.email = @email AND email_address.is_activated = TRUE
)
*/
user := new(User)
err := s.db.WithContext(ctx).
Joins(dbutil.Quote("LEFT JOIN email_address ON email_address.uid = %s.id", "user"), true).
Where(dbutil.Quote("%s.type = ?", "user"), UserTypeIndividual).
Where(s.db.
Where(dbutil.Quote("%[1]s.email = ? AND %[1]s.is_active = ?", "user"), email, true).
Or("email_address.email = ? AND email_address.is_activated = ?", email, true),
).
First(&user).
Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrUserNotExist{args: errutil.Args{"email": email}}
}
return nil, err
}
return user, nil
}
// GetByID returns the user with given ID. It returns ErrUserNotExist when not
// found.
func (s *UsersStore) GetByID(ctx context.Context, id int64) (*User, error) {
user := new(User)
err := s.db.WithContext(ctx).Where("id = ?", id).First(user).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrUserNotExist{args: errutil.Args{"userID": id}}
}
return nil, err
}
return user, nil
}
// GetByUsername returns the user with given username. It returns
// ErrUserNotExist when not found.
func (s *UsersStore) GetByUsername(ctx context.Context, username string) (*User, error) {
user := new(User)
err := s.db.WithContext(ctx).Where("lower_name = ?", strings.ToLower(username)).First(user).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrUserNotExist{args: errutil.Args{"name": username}}
}
return nil, err
}
return user, nil
}
// GetByKeyID returns the owner of given public key ID. It returns
// ErrUserNotExist when not found.
func (s *UsersStore) GetByKeyID(ctx context.Context, keyID int64) (*User, error) {
user := new(User)
err := s.db.WithContext(ctx).
Joins(dbutil.Quote("JOIN public_key ON public_key.owner_id = %s.id", "user")).
Where("public_key.id = ?", keyID).
First(user).
Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrUserNotExist{args: errutil.Args{"keyID": keyID}}
}
return nil, err
}
return user, nil
}
// GetMailableEmailsByUsernames returns a list of verified primary email
// addresses (where email notifications are sent to) of users with given list of
// usernames. Non-existing usernames are ignored.
func (s *UsersStore) GetMailableEmailsByUsernames(ctx context.Context, usernames []string) ([]string, error) {
emails := make([]string, 0, len(usernames))
return emails, s.db.WithContext(ctx).
Model(&User{}).
Select("email").
Where("lower_name IN (?) AND is_active = ?", usernames, true).
Find(&emails).Error
}
// IsUsernameUsed returns true if the given username has been used other than
// the excluded user (a non-positive ID effectively meaning check against all
// users).
func (s *UsersStore) IsUsernameUsed(ctx context.Context, username string, excludeUserID int64) bool {
if username == "" {
return false
}
return s.db.WithContext(ctx).
Select("id").
Where("lower_name = ? AND id != ?", strings.ToLower(username), excludeUserID).
First(&User{}).
Error != gorm.ErrRecordNotFound
}
// List returns a list of users. Results are paginated by given page and page
// size, and sorted by primary key (id) in ascending order.
func (s *UsersStore) List(ctx context.Context, page, pageSize int) ([]*User, error) {
users := make([]*User, 0, pageSize)
return users, s.db.WithContext(ctx).
Where("type = ?", UserTypeIndividual).
Limit(pageSize).Offset((page - 1) * pageSize).
Order("id ASC").
Find(&users).
Error
}
// ListFollowers returns a list of users that are following the given user.
// Results are paginated by given page and page size, and sorted by the time of
// follow in descending order.
func (s *UsersStore) ListFollowers(ctx context.Context, userID int64, page, pageSize int) ([]*User, error) {
/*
Equivalent SQL for PostgreSQL:
SELECT * FROM "user"
LEFT JOIN follow ON follow.user_id = "user".id
WHERE follow.follow_id = @userID
ORDER BY follow.id DESC
LIMIT @limit OFFSET @offset
*/
users := make([]*User, 0, pageSize)
return users, s.db.WithContext(ctx).
Joins(dbutil.Quote("LEFT JOIN follow ON follow.user_id = %s.id", "user")).
Where("follow.follow_id = ?", userID).
Limit(pageSize).Offset((page - 1) * pageSize).
Order("follow.id DESC").
Find(&users).
Error
}
// ListFollowings returns a list of users that are followed by the given user.
// Results are paginated by given page and page size, and sorted by the time of
// follow in descending order.
func (s *UsersStore) ListFollowings(ctx context.Context, userID int64, page, pageSize int) ([]*User, error) {
/*
Equivalent SQL for PostgreSQL:
SELECT * FROM "user"
LEFT JOIN follow ON follow.user_id = "user".id
WHERE follow.user_id = @userID
ORDER BY follow.id DESC
LIMIT @limit OFFSET @offset
*/
users := make([]*User, 0, pageSize)
return users, s.db.WithContext(ctx).
Joins(dbutil.Quote("LEFT JOIN follow ON follow.follow_id = %s.id", "user")).
Where("follow.user_id = ?", userID).
Limit(pageSize).Offset((page - 1) * pageSize).
Order("follow.id DESC").
Find(&users).
Error
}
func searchUserByName(ctx context.Context, db *gorm.DB, userType UserType, keyword string, page, pageSize int, orderBy string) ([]*User, int64, error) {
if keyword == "" {
return []*User{}, 0, nil
}
keyword = "%" + strings.ToLower(keyword) + "%"
tx := db.WithContext(ctx).
Where("type = ? AND (lower_name LIKE ? OR LOWER(full_name) LIKE ?)", userType, keyword, keyword)
var count int64
err := tx.Model(&User{}).Count(&count).Error
if err != nil {
return nil, 0, errors.Wrap(err, "count")
}
users := make([]*User, 0, pageSize)
return users, count, tx.Order(orderBy).Limit(pageSize).Offset((page - 1) * pageSize).Find(&users).Error
}
// SearchByName returns a list of users whose username or full name matches the
// given keyword case-insensitively. Results are paginated by given page and
// page size, and sorted by the given order (e.g. "id DESC"). A total count of
// all results is also returned. If the order is not given, it's up to the
// database to decide.
func (s *UsersStore) SearchByName(ctx context.Context, keyword string, page, pageSize int, orderBy string) ([]*User, int64, error) {
return searchUserByName(ctx, s.db, UserTypeIndividual, keyword, page, pageSize, orderBy)
}
type UpdateUserOptions struct {
LoginSource *int64
LoginName *string
Password *string
// GenerateNewRands indicates whether to force generate new rands for the user.
GenerateNewRands bool
FullName *string
Email *string
Website *string
Location *string
Description *string
MaxRepoCreation *int
LastRepoVisibility *bool
IsActivated *bool
IsAdmin *bool
AllowGitHook *bool
AllowImportLocal *bool
ProhibitLogin *bool
Avatar *string
AvatarEmail *string
}
// Update updates fields for the given user.
func (s *UsersStore) Update(ctx context.Context, userID int64, opts UpdateUserOptions) error {
updates := map[string]any{
"updated_unix": s.db.NowFunc().Unix(),
}
if opts.LoginSource != nil {
updates["login_source"] = *opts.LoginSource
}
if opts.LoginName != nil {
updates["login_name"] = *opts.LoginName
}
if opts.Password != nil {
salt, err := userutil.RandomSalt()
if err != nil {
return errors.Wrap(err, "generate salt")
}
updates["salt"] = salt
updates["passwd"] = userutil.EncodePassword(*opts.Password, salt)
opts.GenerateNewRands = true
}
if opts.GenerateNewRands {
rands, err := userutil.RandomSalt()
if err != nil {
return errors.Wrap(err, "generate rands")
}
updates["rands"] = rands
}
if opts.FullName != nil {
updates["full_name"] = strutil.Truncate(*opts.FullName, 255)
}
if opts.Email != nil {
_, err := s.GetByEmail(ctx, *opts.Email)
if err == nil {
return ErrEmailAlreadyUsed{args: errutil.Args{"email": *opts.Email}}
} else if !IsErrUserNotExist(err) {
return errors.Wrap(err, "check email")
}
updates["email"] = *opts.Email
}
if opts.Website != nil {
updates["website"] = strutil.Truncate(*opts.Website, 255)
}
if opts.Location != nil {
updates["location"] = strutil.Truncate(*opts.Location, 255)
}
if opts.Description != nil {
updates["description"] = strutil.Truncate(*opts.Description, 255)
}
if opts.MaxRepoCreation != nil {
if *opts.MaxRepoCreation < -1 {
*opts.MaxRepoCreation = -1
}
updates["max_repo_creation"] = *opts.MaxRepoCreation
}
if opts.LastRepoVisibility != nil {
updates["last_repo_visibility"] = *opts.LastRepoVisibility
}
if opts.IsActivated != nil {
updates["is_active"] = *opts.IsActivated
}
if opts.IsAdmin != nil {
updates["is_admin"] = *opts.IsAdmin
}
if opts.AllowGitHook != nil {
updates["allow_git_hook"] = *opts.AllowGitHook
}
if opts.AllowImportLocal != nil {
updates["allow_import_local"] = *opts.AllowImportLocal
}
if opts.ProhibitLogin != nil {
updates["prohibit_login"] = *opts.ProhibitLogin
}
if opts.Avatar != nil {
updates["avatar"] = strutil.Truncate(*opts.Avatar, 2048)
}
if opts.AvatarEmail != nil {
updates["avatar_email"] = strutil.Truncate(*opts.AvatarEmail, 255)
}
return s.db.WithContext(ctx).Model(&User{}).Where("id = ?", userID).Updates(updates).Error
}
// UseCustomAvatar uses the given avatar as the user custom avatar.
func (s *UsersStore) UseCustomAvatar(ctx context.Context, userID int64, avatar []byte) error {
err := userutil.SaveAvatar(userID, avatar)
if err != nil {
return errors.Wrap(err, "save avatar")
}
return s.db.WithContext(ctx).
Model(&User{}).
Where("id = ?", userID).
Updates(map[string]any{
"use_custom_avatar": true,
"updated_unix": s.db.NowFunc().Unix(),
}).
Error
}
// AddEmail adds a new email address to given user. It returns
// ErrEmailAlreadyUsed if the email has been verified by another user.
func (s *UsersStore) AddEmail(ctx context.Context, userID int64, email string, isActivated bool) error {
email = strings.ToLower(strings.TrimSpace(email))
_, err := s.GetByEmail(ctx, email)
if err == nil {
return ErrEmailAlreadyUsed{
args: errutil.Args{
"email": email,
},
}
} else if !IsErrUserNotExist(err) {
return errors.Wrap(err, "check user by email")
}
return s.db.WithContext(ctx).Create(
&EmailAddress{
UserID: userID,
Email: email,
IsActivated: isActivated,
},
).Error
}
var _ errutil.NotFound = (*ErrEmailNotExist)(nil)
type ErrEmailNotExist struct {
args errutil.Args
}
// IsErrEmailAddressNotExist returns true if the underlying error has the type
// ErrEmailNotExist.
func IsErrEmailAddressNotExist(err error) bool {
_, ok := errors.Cause(err).(ErrEmailNotExist)
return ok
}
func (err ErrEmailNotExist) Error() string {
return fmt.Sprintf("email address does not exist: %v", err.args)
}
func (ErrEmailNotExist) NotFound() bool {
return true
}
// GetEmail returns the email address of the given user. If `needsActivated` is
// true, only activated email will be returned, otherwise, it may return
// inactivated email addresses. It returns ErrEmailNotExist when no qualified
// email is not found.
func (s *UsersStore) GetEmail(ctx context.Context, userID int64, email string, needsActivated bool) (*EmailAddress, error) {
tx := s.db.WithContext(ctx).Where("uid = ? AND email = ?", userID, email)
if needsActivated {
tx = tx.Where("is_activated = ?", true)
}
emailAddress := new(EmailAddress)
err := tx.First(emailAddress).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrEmailNotExist{
args: errutil.Args{
"email": email,
},
}
}
return nil, err
}
return emailAddress, nil
}
// ListEmails returns all email addresses of the given user. It always includes
// a primary email address.
func (s *UsersStore) ListEmails(ctx context.Context, userID int64) ([]*EmailAddress, error) {
user, err := s.GetByID(ctx, userID)
if err != nil {
return nil, errors.Wrap(err, "get user")
}
var emails []*EmailAddress
err = s.db.WithContext(ctx).Where("uid = ?", userID).Order("id ASC").Find(&emails).Error
if err != nil {
return nil, errors.Wrap(err, "list emails")
}
isPrimaryFound := false
for _, email := range emails {
if email.Email == user.Email {
isPrimaryFound = true
email.IsPrimary = true
break
}
}
// We always want the primary email address displayed, even if it's not in the
// email_address table yet.
if !isPrimaryFound {
emails = append(emails, &EmailAddress{
Email: user.Email,
IsActivated: user.IsActive,
IsPrimary: true,
})
}
return emails, nil
}
// MarkEmailActivated marks the email address of the given user as activated,
// and new rands are generated for the user.
func (s *UsersStore) MarkEmailActivated(ctx context.Context, userID int64, email string) error {
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | true |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/update.go | internal/database/update.go | // Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"context"
"fmt"
"os/exec"
"strings"
"github.com/gogs/git-module"
"github.com/pkg/errors"
)
// CommitToPushCommit transforms a git.Commit to PushCommit type.
func CommitToPushCommit(commit *git.Commit) *PushCommit {
return &PushCommit{
Sha1: commit.ID.String(),
Message: commit.Message,
AuthorEmail: commit.Author.Email,
AuthorName: commit.Author.Name,
CommitterEmail: commit.Committer.Email,
CommitterName: commit.Committer.Name,
Timestamp: commit.Committer.When,
}
}
func CommitsToPushCommits(commits []*git.Commit) *PushCommits {
if len(commits) == 0 {
return &PushCommits{}
}
pcs := make([]*PushCommit, len(commits))
for i := range commits {
pcs[i] = CommitToPushCommit(commits[i])
}
return &PushCommits{len(pcs), pcs, "", nil}
}
type PushUpdateOptions struct {
OldCommitID string
NewCommitID string
FullRefspec string
PusherID int64
PusherName string
RepoUserName string
RepoName string
}
// PushUpdate must be called for any push actions in order to generate necessary
// push action history feeds.
func PushUpdate(opts PushUpdateOptions) (err error) {
ctx := context.TODO()
isNewRef := strings.HasPrefix(opts.OldCommitID, git.EmptyID)
isDelRef := strings.HasPrefix(opts.NewCommitID, git.EmptyID)
if isNewRef && isDelRef {
return fmt.Errorf("both old and new revisions are %q", git.EmptyID)
}
repoPath := RepoPath(opts.RepoUserName, opts.RepoName)
gitUpdate := exec.Command("git", "update-server-info")
gitUpdate.Dir = repoPath
if err = gitUpdate.Run(); err != nil {
return fmt.Errorf("run 'git update-server-info': %v", err)
}
gitRepo, err := git.Open(repoPath)
if err != nil {
return fmt.Errorf("open repository: %v", err)
}
owner, err := Handle.Users().GetByUsername(ctx, opts.RepoUserName)
if err != nil {
return fmt.Errorf("GetUserByName: %v", err)
}
repo, err := GetRepositoryByName(owner.ID, opts.RepoName)
if err != nil {
return fmt.Errorf("GetRepositoryByName: %v", err)
}
if err = repo.UpdateSize(); err != nil {
return fmt.Errorf("UpdateSize: %v", err)
}
// Push tags
if strings.HasPrefix(opts.FullRefspec, git.RefsTags) {
err := Handle.Actions().PushTag(ctx,
PushTagOptions{
Owner: owner,
Repo: repo,
PusherName: opts.PusherName,
RefFullName: opts.FullRefspec,
NewCommitID: opts.NewCommitID,
},
)
if err != nil {
return errors.Wrap(err, "create action for push tag")
}
return nil
}
var commits []*git.Commit
// Skip read parent commits when delete branch
if !isDelRef {
// Push new branch
newCommit, err := gitRepo.CatFileCommit(opts.NewCommitID)
if err != nil {
return fmt.Errorf("GetCommit [commit_id: %s]: %v", opts.NewCommitID, err)
}
if isNewRef {
commits, err = newCommit.Ancestors(git.LogOptions{MaxCount: 9})
if err != nil {
return fmt.Errorf("CommitsBeforeLimit [commit_id: %s]: %v", newCommit.ID, err)
}
commits = append([]*git.Commit{newCommit}, commits...)
} else {
commits, err = newCommit.CommitsAfter(opts.OldCommitID)
if err != nil {
return fmt.Errorf("CommitsBeforeUntil [commit_id: %s]: %v", opts.OldCommitID, err)
}
}
}
err = Handle.Actions().CommitRepo(ctx,
CommitRepoOptions{
Owner: owner,
Repo: repo,
PusherName: opts.PusherName,
RefFullName: opts.FullRefspec,
OldCommitID: opts.OldCommitID,
NewCommitID: opts.NewCommitID,
Commits: CommitsToPushCommits(commits),
},
)
if err != nil {
return errors.Wrap(err, "create action for commit push")
}
return nil
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/mirror_test.go | internal/database/mirror_test.go | // Copyright 2017 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"testing"
"github.com/stretchr/testify/assert"
)
func Test_parseRemoteUpdateOutput(t *testing.T) {
tests := []struct {
output string
expResults []*mirrorSyncResult
}{
{
`
From https://try.gogs.io/unknwon/upsteam
* [new branch] develop -> develop
b0bb24f..1d85a4f master -> master
- [deleted] (none) -> bugfix
`,
[]*mirrorSyncResult{
{"develop", gitShortEmptyID, ""},
{"master", "b0bb24f", "1d85a4f"},
{"bugfix", "", gitShortEmptyID},
},
},
}
for _, test := range tests {
t.Run("", func(t *testing.T) {
assert.Equal(t, test.expResults, parseRemoteUpdateOutput(test.output))
})
}
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/org.go | internal/database/org.go | // Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"context"
"errors"
"fmt"
"os"
"strings"
"xorm.io/builder"
"xorm.io/xorm"
"gogs.io/gogs/internal/errutil"
"gogs.io/gogs/internal/repoutil"
"gogs.io/gogs/internal/userutil"
)
var ErrOrgNotExist = errors.New("Organization does not exist")
// IsOwnedBy returns true if given user is in the owner team.
func (org *User) IsOwnedBy(userID int64) bool {
return IsOrganizationOwner(org.ID, userID)
}
// IsOrgMember returns true if given user is member of organization.
func (org *User) IsOrgMember(uid int64) bool {
return org.IsOrganization() && IsOrganizationMember(org.ID, uid)
}
func (org *User) getTeam(e Engine, name string) (*Team, error) {
return getTeamOfOrgByName(e, org.ID, name)
}
// GetTeamOfOrgByName returns named team of organization.
func (org *User) GetTeam(name string) (*Team, error) {
return org.getTeam(x, name)
}
func (org *User) getOwnerTeam(e Engine) (*Team, error) {
return org.getTeam(e, ownerTeamName)
}
// GetOwnerTeam returns owner team of organization.
func (org *User) GetOwnerTeam() (*Team, error) {
return org.getOwnerTeam(x)
}
func (org *User) getTeams(e Engine) (err error) {
org.Teams, err = getTeamsByOrgID(e, org.ID)
return err
}
// GetTeams returns all teams that belong to organization.
func (org *User) GetTeams() error {
return org.getTeams(x)
}
// TeamsHaveAccessToRepo returns all teams that have given access level to the repository.
func (org *User) TeamsHaveAccessToRepo(repoID int64, mode AccessMode) ([]*Team, error) {
return GetTeamsHaveAccessToRepo(org.ID, repoID, mode)
}
// GetMembers returns all members of organization.
func (org *User) GetMembers(limit int) error {
ous, err := GetOrgUsersByOrgID(org.ID, limit)
if err != nil {
return err
}
org.Members = make([]*User, len(ous))
for i, ou := range ous {
org.Members[i], err = Handle.Users().GetByID(context.TODO(), ou.UID)
if err != nil {
return err
}
}
return nil
}
// AddMember adds new member to organization.
func (org *User) AddMember(uid int64) error {
return AddOrgUser(org.ID, uid)
}
// RemoveMember removes member from organization.
func (org *User) RemoveMember(uid int64) error {
return RemoveOrgUser(org.ID, uid)
}
func (org *User) removeOrgRepo(e Engine, repoID int64) error {
return removeOrgRepo(e, org.ID, repoID)
}
// RemoveOrgRepo removes all team-repository relations of organization.
func (org *User) RemoveOrgRepo(repoID int64) error {
return org.removeOrgRepo(x, repoID)
}
// CreateOrganization creates record of a new organization.
func CreateOrganization(org, owner *User) (err error) {
if err = isUsernameAllowed(org.Name); err != nil {
return err
}
if Handle.Users().IsUsernameUsed(context.TODO(), org.Name, 0) {
return ErrUserAlreadyExist{
args: errutil.Args{
"name": org.Name,
},
}
}
org.LowerName = strings.ToLower(org.Name)
if org.Rands, err = userutil.RandomSalt(); err != nil {
return err
}
if org.Salt, err = userutil.RandomSalt(); err != nil {
return err
}
org.UseCustomAvatar = true
org.MaxRepoCreation = -1
org.NumTeams = 1
org.NumMembers = 1
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if _, err = sess.Insert(org); err != nil {
return fmt.Errorf("insert organization: %v", err)
}
_ = userutil.GenerateRandomAvatar(org.ID, org.Name, org.Email)
// Add initial creator to organization and owner team.
if _, err = sess.Insert(&OrgUser{
UID: owner.ID,
OrgID: org.ID,
IsOwner: true,
NumTeams: 1,
}); err != nil {
return fmt.Errorf("insert org-user relation: %v", err)
}
// Create default owner team.
t := &Team{
OrgID: org.ID,
LowerName: strings.ToLower(ownerTeamName),
Name: ownerTeamName,
Authorize: AccessModeOwner,
NumMembers: 1,
}
if _, err = sess.Insert(t); err != nil {
return fmt.Errorf("insert owner team: %v", err)
}
if _, err = sess.Insert(&TeamUser{
UID: owner.ID,
OrgID: org.ID,
TeamID: t.ID,
}); err != nil {
return fmt.Errorf("insert team-user relation: %v", err)
}
if err = os.MkdirAll(repoutil.UserPath(org.Name), os.ModePerm); err != nil {
return fmt.Errorf("create directory: %v", err)
}
return sess.Commit()
}
// GetOrgByName returns organization by given name.
func GetOrgByName(name string) (*User, error) {
if name == "" {
return nil, ErrOrgNotExist
}
u := &User{
LowerName: strings.ToLower(name),
Type: UserTypeOrganization,
}
has, err := x.Get(u)
if err != nil {
return nil, err
} else if !has {
return nil, ErrOrgNotExist
}
return u, nil
}
// CountOrganizations returns number of organizations.
func CountOrganizations() int64 {
count, _ := x.Where("type=1").Count(new(User))
return count
}
// Organizations returns number of organizations in given page.
func Organizations(page, pageSize int) ([]*User, error) {
orgs := make([]*User, 0, pageSize)
return orgs, x.Limit(pageSize, (page-1)*pageSize).Where("type=1").Asc("id").Find(&orgs)
}
// deleteBeans deletes all given beans, beans should contain delete conditions.
func deleteBeans(e Engine, beans ...any) (err error) {
for i := range beans {
if _, err = e.Delete(beans[i]); err != nil {
return err
}
}
return nil
}
// DeleteOrganization completely and permanently deletes everything of organization.
func DeleteOrganization(org *User) error {
err := Handle.Users().DeleteByID(context.TODO(), org.ID, false)
if err != nil {
return err
}
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if err = deleteBeans(sess,
&Team{OrgID: org.ID},
&OrgUser{OrgID: org.ID},
&TeamUser{OrgID: org.ID},
); err != nil {
return fmt.Errorf("deleteBeans: %v", err)
}
return sess.Commit()
}
// ________ ____ ___
// \_____ \_______ ____ | | \______ ___________
// / | \_ __ \/ ___\| | / ___// __ \_ __ \
// / | \ | \/ /_/ > | /\___ \\ ___/| | \/
// \_______ /__| \___ /|______//____ >\___ >__|
// \/ /_____/ \/ \/
// OrgUser represents relations of organizations and their members.
type OrgUser struct {
ID int64 `gorm:"primaryKey"`
UID int64 `xorm:"uid INDEX UNIQUE(s)" gorm:"column:uid;uniqueIndex:org_user_user_org_unique;index;not null"`
OrgID int64 `xorm:"INDEX UNIQUE(s)" gorm:"uniqueIndex:org_user_user_org_unique;index;not null"`
IsPublic bool `gorm:"not null;default:FALSE"`
IsOwner bool `gorm:"not null;default:FALSE"`
NumTeams int `gorm:"not null;default:0"`
}
// IsOrganizationOwner returns true if given user is in the owner team.
func IsOrganizationOwner(orgID, userID int64) bool {
has, _ := x.Where("is_owner = ?", true).And("uid = ?", userID).And("org_id = ?", orgID).Get(new(OrgUser))
return has
}
// IsOrganizationMember returns true if given user is member of organization.
func IsOrganizationMember(orgID, uid int64) bool {
has, _ := x.Where("uid=?", uid).And("org_id=?", orgID).Get(new(OrgUser))
return has
}
// IsPublicMembership returns true if given user public his/her membership.
func IsPublicMembership(orgID, uid int64) bool {
has, _ := x.Where("uid=?", uid).And("org_id=?", orgID).And("is_public=?", true).Get(new(OrgUser))
return has
}
func getOrgsByUserID(sess *xorm.Session, userID int64, showAll bool) ([]*User, error) {
orgs := make([]*User, 0, 10)
if !showAll {
sess.And("`org_user`.is_public=?", true)
}
return orgs, sess.And("`org_user`.uid=?", userID).
Join("INNER", "`org_user`", "`org_user`.org_id=`user`.id").Find(&orgs)
}
// GetOrgsByUserID returns a list of organizations that the given user ID
// has joined.
func GetOrgsByUserID(userID int64, showAll bool) ([]*User, error) {
return getOrgsByUserID(x.NewSession(), userID, showAll)
}
func getOwnedOrgsByUserID(sess *xorm.Session, userID int64) ([]*User, error) {
orgs := make([]*User, 0, 10)
return orgs, sess.Where("`org_user`.uid=?", userID).And("`org_user`.is_owner=?", true).
Join("INNER", "`org_user`", "`org_user`.org_id=`user`.id").Find(&orgs)
}
// GetOwnedOrgsByUserID returns a list of organizations are owned by given user ID.
func GetOwnedOrgsByUserID(userID int64) ([]*User, error) {
sess := x.NewSession()
return getOwnedOrgsByUserID(sess, userID)
}
// GetOwnedOrganizationsByUserIDDesc returns a list of organizations are owned by
// given user ID, ordered descending by the given condition.
func GetOwnedOrgsByUserIDDesc(userID int64, desc string) ([]*User, error) {
sess := x.NewSession()
return getOwnedOrgsByUserID(sess.Desc(desc), userID)
}
func getOrgUsersByOrgID(e Engine, orgID int64, limit int) ([]*OrgUser, error) {
orgUsers := make([]*OrgUser, 0, 10)
sess := e.Where("org_id=?", orgID)
if limit > 0 {
sess = sess.Limit(limit)
}
return orgUsers, sess.Find(&orgUsers)
}
// GetOrgUsersByOrgID returns all organization-user relations by organization ID.
func GetOrgUsersByOrgID(orgID int64, limit int) ([]*OrgUser, error) {
return getOrgUsersByOrgID(x, orgID, limit)
}
// ChangeOrgUserStatus changes public or private membership status.
func ChangeOrgUserStatus(orgID, uid int64, public bool) error {
ou := new(OrgUser)
has, err := x.Where("uid=?", uid).And("org_id=?", orgID).Get(ou)
if err != nil {
return err
} else if !has {
return nil
}
ou.IsPublic = public
_, err = x.Id(ou.ID).AllCols().Update(ou)
return err
}
// AddOrgUser adds new user to given organization.
func AddOrgUser(orgID, uid int64) error {
if IsOrganizationMember(orgID, uid) {
return nil
}
sess := x.NewSession()
defer sess.Close()
if err := sess.Begin(); err != nil {
return err
}
ou := &OrgUser{
UID: uid,
OrgID: orgID,
}
if _, err := sess.Insert(ou); err != nil {
return err
} else if _, err = sess.Exec("UPDATE `user` SET num_members = num_members + 1 WHERE id = ?", orgID); err != nil {
return err
}
return sess.Commit()
}
// RemoveOrgUser removes user from given organization.
func RemoveOrgUser(orgID, userID int64) error {
ou := new(OrgUser)
has, err := x.Where("uid=?", userID).And("org_id=?", orgID).Get(ou)
if err != nil {
return fmt.Errorf("get org-user: %v", err)
} else if !has {
return nil
}
user, err := Handle.Users().GetByID(context.TODO(), userID)
if err != nil {
return fmt.Errorf("GetUserByID [%d]: %v", userID, err)
}
org, err := Handle.Users().GetByID(context.TODO(), orgID)
if err != nil {
return fmt.Errorf("GetUserByID [%d]: %v", orgID, err)
}
// FIXME: only need to get IDs here, not all fields of repository.
repos, _, err := org.GetUserRepositories(user.ID, 1, org.NumRepos)
if err != nil {
return fmt.Errorf("GetUserRepositories [%d]: %v", user.ID, err)
}
// Check if the user to delete is the last member in owner team.
if IsOrganizationOwner(orgID, userID) {
t, err := org.GetOwnerTeam()
if err != nil {
return err
}
if t.NumMembers == 1 {
return ErrLastOrgOwner{UID: userID}
}
}
sess := x.NewSession()
defer sess.Close()
if err := sess.Begin(); err != nil {
return err
}
if _, err := sess.ID(ou.ID).Delete(ou); err != nil {
return err
} else if _, err = sess.Exec("UPDATE `user` SET num_members=num_members-1 WHERE id=?", orgID); err != nil {
return err
}
// Delete all repository accesses and unwatch them.
repoIDs := make([]int64, 0, len(repos))
for i := range repos {
repoIDs = append(repoIDs, repos[i].ID)
if err = watchRepo(sess, user.ID, repos[i].ID, false); err != nil {
return err
}
}
if len(repoIDs) > 0 {
if _, err = sess.Where("user_id = ?", user.ID).In("repo_id", repoIDs).Delete(new(Access)); err != nil {
return err
}
}
// Delete member in his/her teams.
teams, err := getUserTeams(sess, org.ID, user.ID)
if err != nil {
return err
}
for _, t := range teams {
if err = removeTeamMember(sess, org.ID, t.ID, user.ID); err != nil {
return err
}
}
return sess.Commit()
}
func removeOrgRepo(e Engine, orgID, repoID int64) error {
_, err := e.Delete(&TeamRepo{
OrgID: orgID,
RepoID: repoID,
})
return err
}
// RemoveOrgRepo removes all team-repository relations of given organization.
func RemoveOrgRepo(orgID, repoID int64) error {
return removeOrgRepo(x, orgID, repoID)
}
func (org *User) getUserTeams(e Engine, userID int64, cols ...string) ([]*Team, error) {
teams := make([]*Team, 0, org.NumTeams)
return teams, e.Where("team_user.org_id = ?", org.ID).
And("team_user.uid = ?", userID).
Join("INNER", "team_user", "team_user.team_id = team.id").
Cols(cols...).Find(&teams)
}
// GetUserTeamIDs returns of all team IDs of the organization that user is member of.
func (org *User) GetUserTeamIDs(userID int64) ([]int64, error) {
teams, err := org.getUserTeams(x, userID, "team.id")
if err != nil {
return nil, fmt.Errorf("getUserTeams [%d]: %v", userID, err)
}
teamIDs := make([]int64, len(teams))
for i := range teams {
teamIDs[i] = teams[i].ID
}
return teamIDs, nil
}
// GetTeams returns all teams that belong to organization,
// and that the user has joined.
func (org *User) GetUserTeams(userID int64) ([]*Team, error) {
return org.getUserTeams(x, userID)
}
// GetUserRepositories returns a range of repositories in organization which the user has access to,
// and total number of records based on given condition.
func (org *User) GetUserRepositories(userID int64, page, pageSize int) ([]*Repository, int64, error) {
teamIDs, err := org.GetUserTeamIDs(userID)
if err != nil {
return nil, 0, fmt.Errorf("GetUserTeamIDs: %v", err)
}
if len(teamIDs) == 0 {
// user has no team but "IN ()" is invalid SQL
teamIDs = []int64{-1} // there is no team with id=-1
}
var teamRepoIDs []int64
if err = x.Table("team_repo").In("team_id", teamIDs).Distinct("repo_id").Find(&teamRepoIDs); err != nil {
return nil, 0, fmt.Errorf("get team repository IDs: %v", err)
}
if len(teamRepoIDs) == 0 {
// team has no repo but "IN ()" is invalid SQL
teamRepoIDs = []int64{-1} // there is no repo with id=-1
}
if page <= 0 {
page = 1
}
repos := make([]*Repository, 0, pageSize)
if err = x.Where("owner_id = ?", org.ID).
And(builder.Or(
builder.And(builder.Expr("is_private = ?", false), builder.Expr("is_unlisted = ?", false)),
builder.In("id", teamRepoIDs))).
Desc("updated_unix").
Limit(pageSize, (page-1)*pageSize).
Find(&repos); err != nil {
return nil, 0, fmt.Errorf("get user repositories: %v", err)
}
repoCount, err := x.Where("owner_id = ?", org.ID).
And(builder.Or(
builder.Expr("is_private = ?", false),
builder.In("id", teamRepoIDs))).
Count(new(Repository))
if err != nil {
return nil, 0, fmt.Errorf("count user repositories: %v", err)
}
return repos, repoCount, nil
}
// GetUserMirrorRepositories returns mirror repositories of the organization which the user has access to.
func (org *User) GetUserMirrorRepositories(userID int64) ([]*Repository, error) {
teamIDs, err := org.GetUserTeamIDs(userID)
if err != nil {
return nil, fmt.Errorf("GetUserTeamIDs: %v", err)
}
if len(teamIDs) == 0 {
teamIDs = []int64{-1}
}
var teamRepoIDs []int64
err = x.Table("team_repo").In("team_id", teamIDs).Distinct("repo_id").Find(&teamRepoIDs)
if err != nil {
return nil, fmt.Errorf("get team repository ids: %v", err)
}
if len(teamRepoIDs) == 0 {
// team has no repo but "IN ()" is invalid SQL
teamRepoIDs = []int64{-1} // there is no repo with id=-1
}
repos := make([]*Repository, 0, 10)
if err = x.Where("owner_id = ?", org.ID).
And("is_private = ?", false).
Or(builder.In("id", teamRepoIDs)).
And("is_mirror = ?", true). // Don't move up because it's an independent condition
Desc("updated_unix").
Find(&repos); err != nil {
return nil, fmt.Errorf("get user repositories: %v", err)
}
return repos, nil
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/permissions.go | internal/database/permissions.go | // Copyright 2020 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"context"
"github.com/pkg/errors"
"gorm.io/gorm"
log "unknwon.dev/clog/v2"
)
// Access represents the highest access level of a user has to a repository. The
// only access type that is not in this table is the real owner of a repository.
// In case of an organization repository, the members of the owners team are in
// this table.
type Access struct {
ID int64 `gorm:"primaryKey"`
UserID int64 `xorm:"UNIQUE(s)" gorm:"uniqueIndex:access_user_repo_unique;not null"`
RepoID int64 `xorm:"UNIQUE(s)" gorm:"uniqueIndex:access_user_repo_unique;not null"`
Mode AccessMode `gorm:"not null"`
}
// AccessMode is the access mode of a user has to a repository.
type AccessMode int
const (
AccessModeNone AccessMode = iota // 0
AccessModeRead // 1
AccessModeWrite // 2
AccessModeAdmin // 3
AccessModeOwner // 4
)
func (mode AccessMode) String() string {
switch mode {
case AccessModeRead:
return "read"
case AccessModeWrite:
return "write"
case AccessModeAdmin:
return "admin"
case AccessModeOwner:
return "owner"
default:
return "none"
}
}
// ParseAccessMode returns corresponding access mode to given permission string.
func ParseAccessMode(permission string) AccessMode {
switch permission {
case "write":
return AccessModeWrite
case "admin":
return AccessModeAdmin
default:
return AccessModeRead
}
}
// PermissionsStore is the storage layer for repository permissions.
type PermissionsStore struct {
db *gorm.DB
}
func newPermissionsStore(db *gorm.DB) *PermissionsStore {
return &PermissionsStore{db: db}
}
type AccessModeOptions struct {
OwnerID int64 // The ID of the repository owner.
Private bool // Whether the repository is private.
}
// AccessMode returns the access mode of given user has to the repository.
func (s *PermissionsStore) AccessMode(ctx context.Context, userID, repoID int64, opts AccessModeOptions) (mode AccessMode) {
if repoID <= 0 {
return AccessModeNone
}
// Everyone has read access to public repository.
if !opts.Private {
mode = AccessModeRead
}
// Anonymous user gets the default access.
if userID <= 0 {
return mode
}
if userID == opts.OwnerID {
return AccessModeOwner
}
access := new(Access)
err := s.db.WithContext(ctx).Where("user_id = ? AND repo_id = ?", userID, repoID).First(access).Error
if err != nil {
if !errors.Is(err, gorm.ErrRecordNotFound) {
log.Error("Failed to get access [user_id: %d, repo_id: %d]: %v", userID, repoID, err)
}
return mode
}
return access.Mode
}
// Authorize returns true if the user has as good as desired access mode to the
// repository.
func (s *PermissionsStore) Authorize(ctx context.Context, userID, repoID int64, desired AccessMode, opts AccessModeOptions) bool {
return desired <= s.AccessMode(ctx, userID, repoID, opts)
}
// SetRepoPerms does a full update to which users have which level of access to
// given repository. Keys of the "accessMap" are user IDs.
func (s *PermissionsStore) SetRepoPerms(ctx context.Context, repoID int64, accessMap map[int64]AccessMode) error {
records := make([]*Access, 0, len(accessMap))
for userID, mode := range accessMap {
records = append(records, &Access{
UserID: userID,
RepoID: repoID,
Mode: mode,
})
}
return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
err := tx.Where("repo_id = ?", repoID).Delete(new(Access)).Error
if err != nil {
return err
}
return tx.Create(&records).Error
})
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/access_tokens_test.go | internal/database/access_tokens_test.go | // Copyright 2020 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package database
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gorm.io/gorm"
"gogs.io/gogs/internal/errutil"
)
func TestAccessToken_BeforeCreate(t *testing.T) {
now := time.Now()
db := &gorm.DB{
Config: &gorm.Config{
SkipDefaultTransaction: true,
NowFunc: func() time.Time {
return now
},
},
}
t.Run("CreatedUnix has been set", func(t *testing.T) {
token := &AccessToken{
CreatedUnix: 1,
}
_ = token.BeforeCreate(db)
assert.Equal(t, int64(1), token.CreatedUnix)
assert.Equal(t, int64(0), token.UpdatedUnix) // Do not set UpdatedUnix until it is used.
})
t.Run("CreatedUnix has not been set", func(t *testing.T) {
token := &AccessToken{}
_ = token.BeforeCreate(db)
assert.Equal(t, db.NowFunc().Unix(), token.CreatedUnix)
assert.Equal(t, int64(0), token.UpdatedUnix) // Do not set UpdatedUnix until it is used.
})
}
func TestAccessToken_AfterFind(t *testing.T) {
now := time.Now()
db := &gorm.DB{
Config: &gorm.Config{
SkipDefaultTransaction: true,
NowFunc: func() time.Time {
return now
},
},
}
t.Run("UpdatedUnix has been set and within 7 days", func(t *testing.T) {
token := &AccessToken{
CreatedUnix: now.Unix(),
UpdatedUnix: now.Add(time.Second).Unix(),
}
_ = token.AfterFind(db)
assert.Equal(t, token.CreatedUnix, token.Created.Unix())
assert.Equal(t, token.UpdatedUnix, token.Updated.Unix())
assert.True(t, token.HasUsed)
assert.True(t, token.HasRecentActivity)
})
t.Run("UpdatedUnix has been set and not within 7 days", func(t *testing.T) {
token := &AccessToken{
CreatedUnix: now.Add(-1 * 9 * 24 * time.Hour).Unix(),
UpdatedUnix: now.Add(-1 * 8 * 24 * time.Hour).Unix(),
}
_ = token.AfterFind(db)
assert.Equal(t, token.CreatedUnix, token.Created.Unix())
assert.Equal(t, token.UpdatedUnix, token.Updated.Unix())
assert.True(t, token.HasUsed)
assert.False(t, token.HasRecentActivity)
})
t.Run("UpdatedUnix has not been set", func(t *testing.T) {
token := &AccessToken{
CreatedUnix: now.Unix(),
}
_ = token.AfterFind(db)
assert.Equal(t, token.CreatedUnix, token.Created.Unix())
assert.True(t, token.Updated.IsZero())
assert.False(t, token.HasUsed)
assert.False(t, token.HasRecentActivity)
})
}
func TestAccessTokens(t *testing.T) {
if testing.Short() {
t.Skip()
}
t.Parallel()
ctx := context.Background()
s := &AccessTokensStore{
db: newTestDB(t, "AccessTokensStore"),
}
for _, tc := range []struct {
name string
test func(t *testing.T, ctx context.Context, s *AccessTokensStore)
}{
{"Create", accessTokensCreate},
{"DeleteByID", accessTokensDeleteByID},
{"GetBySHA1", accessTokensGetBySHA},
{"List", accessTokensList},
{"Touch", accessTokensTouch},
} {
t.Run(tc.name, func(t *testing.T) {
t.Cleanup(func() {
err := clearTables(t, s.db)
require.NoError(t, err)
})
tc.test(t, ctx, s)
})
if t.Failed() {
break
}
}
}
func accessTokensCreate(t *testing.T, ctx context.Context, s *AccessTokensStore) {
// Create first access token with name "Test"
token, err := s.Create(ctx, 1, "Test")
require.NoError(t, err)
assert.Equal(t, int64(1), token.UserID)
assert.Equal(t, "Test", token.Name)
assert.Equal(t, 40, len(token.Sha1), "sha1 length")
// Get it back and check the Created field
token, err = s.GetBySHA1(ctx, token.Sha1)
require.NoError(t, err)
assert.Equal(t, s.db.NowFunc().Format(time.RFC3339), token.Created.UTC().Format(time.RFC3339))
// Try create second access token with same name should fail
_, err = s.Create(ctx, token.UserID, token.Name)
wantErr := ErrAccessTokenAlreadyExist{
args: errutil.Args{
"userID": token.UserID,
"name": token.Name,
},
}
assert.Equal(t, wantErr, err)
}
func accessTokensDeleteByID(t *testing.T, ctx context.Context, s *AccessTokensStore) {
// Create an access token with name "Test"
token, err := s.Create(ctx, 1, "Test")
require.NoError(t, err)
// Delete a token with mismatched user ID is noop
err = s.DeleteByID(ctx, 2, token.ID)
require.NoError(t, err)
// We should be able to get it back
_, err = s.GetBySHA1(ctx, token.Sha1)
require.NoError(t, err)
// Now delete this token with correct user ID
err = s.DeleteByID(ctx, token.UserID, token.ID)
require.NoError(t, err)
// We should get token not found error
_, err = s.GetBySHA1(ctx, token.Sha1)
wantErr := ErrAccessTokenNotExist{
args: errutil.Args{
"sha": token.Sha1,
},
}
assert.Equal(t, wantErr, err)
}
func accessTokensGetBySHA(t *testing.T, ctx context.Context, s *AccessTokensStore) {
// Create an access token with name "Test"
token, err := s.Create(ctx, 1, "Test")
require.NoError(t, err)
// We should be able to get it back
_, err = s.GetBySHA1(ctx, token.Sha1)
require.NoError(t, err)
// Try to get a non-existent token
_, err = s.GetBySHA1(ctx, "bad_sha")
wantErr := ErrAccessTokenNotExist{
args: errutil.Args{
"sha": "bad_sha",
},
}
assert.Equal(t, wantErr, err)
}
func accessTokensList(t *testing.T, ctx context.Context, s *AccessTokensStore) {
// Create two access tokens for user 1
_, err := s.Create(ctx, 1, "user1_1")
require.NoError(t, err)
_, err = s.Create(ctx, 1, "user1_2")
require.NoError(t, err)
// Create one access token for user 2
_, err = s.Create(ctx, 2, "user2_1")
require.NoError(t, err)
// List all access tokens for user 1
tokens, err := s.List(ctx, 1)
require.NoError(t, err)
require.Equal(t, 2, len(tokens), "number of tokens")
assert.Equal(t, int64(1), tokens[0].UserID)
assert.Equal(t, "user1_1", tokens[0].Name)
assert.Equal(t, int64(1), tokens[1].UserID)
assert.Equal(t, "user1_2", tokens[1].Name)
}
func accessTokensTouch(t *testing.T, ctx context.Context, s *AccessTokensStore) {
// Create an access token with name "Test"
token, err := s.Create(ctx, 1, "Test")
require.NoError(t, err)
// Updated field is zero now
assert.True(t, token.Updated.IsZero())
err = s.Touch(ctx, token.ID)
require.NoError(t, err)
// Get back from DB should have Updated set
token, err = s.GetBySHA1(ctx, token.Sha1)
require.NoError(t, err)
assert.Equal(t, s.db.NowFunc().Format(time.RFC3339), token.Updated.UTC().Format(time.RFC3339))
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/errors/errors.go | internal/database/errors/errors.go | // Copyright 2017 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package errors
import "errors"
var ErrInternalServerError = errors.New("internal server error")
// New is a wrapper of real errors.New function.
func New(text string) error {
return errors.New(text)
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/errors/repo.go | internal/database/errors/repo.go | // Copyright 2017 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package errors
import (
"fmt"
)
type InvalidRepoReference struct {
Ref string
}
func IsInvalidRepoReference(err error) bool {
_, ok := err.(InvalidRepoReference)
return ok
}
func (err InvalidRepoReference) Error() string {
return fmt.Sprintf("invalid repository reference [ref: %s]", err.Ref)
}
type MirrorNotExist struct {
RepoID int64
}
func IsMirrorNotExist(err error) bool {
_, ok := err.(MirrorNotExist)
return ok
}
func (err MirrorNotExist) Error() string {
return fmt.Sprintf("mirror does not exist [repo_id: %d]", err.RepoID)
}
type BranchAlreadyExists struct {
Name string
}
func IsBranchAlreadyExists(err error) bool {
_, ok := err.(BranchAlreadyExists)
return ok
}
func (err BranchAlreadyExists) Error() string {
return fmt.Sprintf("branch already exists [name: %s]", err.Name)
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/migrations/v20.go | internal/database/migrations/v20.go | // Copyright 2022 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package migrations
import (
"github.com/pkg/errors"
"gorm.io/gorm"
"gogs.io/gogs/internal/cryptoutil"
)
func migrateAccessTokenToSHA256(db *gorm.DB) error {
type accessToken struct {
ID int64
Sha1 string
SHA256 string `gorm:"TYPE:VARCHAR(64)"`
}
if db.Migrator().HasColumn(&accessToken{}, "SHA256") {
return errMigrationSkipped
}
return db.Transaction(func(tx *gorm.DB) error {
// 1. Add column without constraints because all rows have NULL values for the
// "sha256" column.
err := tx.Migrator().AddColumn(&accessToken{}, "SHA256")
if err != nil {
return errors.Wrap(err, "add column")
}
// 2. Generate SHA256 for existing rows from their values in the "sha1" column.
var accessTokens []*accessToken
err = tx.Where("sha256 IS NULL").Find(&accessTokens).Error
if err != nil {
return errors.Wrap(err, "list")
}
for _, t := range accessTokens {
sha256 := cryptoutil.SHA256(t.Sha1)
err = tx.Model(&accessToken{}).Where("id = ?", t.ID).Update("sha256", sha256).Error
if err != nil {
return errors.Wrap(err, "update")
}
}
// 3. We are now safe to apply constraints to the "sha256" column.
type accessTokenWithConstraint struct {
SHA256 string `gorm:"type:VARCHAR(64);unique;not null"`
}
err = tx.Table("access_token").AutoMigrate(&accessTokenWithConstraint{})
if err != nil {
return errors.Wrap(err, "auto migrate")
}
return nil
})
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/migrations/v21_test.go | internal/database/migrations/v21_test.go | // Copyright 2022 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package migrations
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gogs.io/gogs/internal/dbtest"
)
type actionPreV21 struct {
ID int64 `gorm:"primaryKey"`
UserID int64
OpType int
ActUserID int64
ActUserName string
RepoID int64 `gorm:"index"`
RepoUserName string
RepoName string
RefName string
IsPrivate bool `gorm:"not null;default:FALSE"`
Content string
CreatedUnix int64
}
func (*actionPreV21) TableName() string {
return "action"
}
type actionV21 struct {
ID int64 `gorm:"primaryKey"`
UserID int64 `gorm:"index"`
OpType int
ActUserID int64
ActUserName string
RepoID int64 `gorm:"index"`
RepoUserName string
RepoName string
RefName string
IsPrivate bool `gorm:"not null;default:FALSE"`
Content string
CreatedUnix int64
}
func (*actionV21) TableName() string {
return "action"
}
func TestAddIndexToActionUserID(t *testing.T) {
if testing.Short() {
t.Skip()
}
t.Parallel()
db := dbtest.NewDB(t, "addIndexToActionUserID", new(actionPreV21))
err := db.Create(
&actionPreV21{
ID: 1,
UserID: 1,
OpType: 1,
ActUserID: 1,
ActUserName: "alice",
RepoID: 1,
RepoUserName: "alice",
RepoName: "example",
RefName: "main",
IsPrivate: false,
CreatedUnix: db.NowFunc().Unix(),
},
).Error
require.NoError(t, err)
assert.False(t, db.Migrator().HasIndex(&actionV21{}, "UserID"))
err = addIndexToActionUserID(db)
require.NoError(t, err)
assert.True(t, db.Migrator().HasIndex(&actionV21{}, "UserID"))
// Re-run should be skipped
err = addIndexToActionUserID(db)
require.Equal(t, errMigrationSkipped, err)
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/migrations/migrations.go | internal/database/migrations/migrations.go | // Copyright 2015 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package migrations
import (
"github.com/pkg/errors"
"gorm.io/gorm"
log "unknwon.dev/clog/v2"
)
const minDBVersion = 19
type Migration interface {
Description() string
Migrate(*gorm.DB) error
}
type migration struct {
description string
migrate func(*gorm.DB) error
}
func NewMigration(desc string, fn func(*gorm.DB) error) Migration {
return &migration{desc, fn}
}
func (m *migration) Description() string {
return m.description
}
func (m *migration) Migrate(db *gorm.DB) error {
return m.migrate(db)
}
// Version represents the version table. It should have only one row with `id == 1`.
type Version struct {
ID int64
Version int64
}
// This is a sequence of migrations. Add new migrations to the bottom of the list.
// If you want to "retire" a migration, remove it from the top of the list and
// update _MIN_VER_DB accordingly
var migrations = []Migration{
// v0 -> v4 : before 0.6.0 -> last support 0.7.33
// v4 -> v10: before 0.7.0 -> last support 0.9.141
// v10 -> v19: before 0.11.55 -> last support 0.12.0
// Add new migration here, example:
// v18 -> v19:v0.11.55
// NewMigration("clean unlinked webhook and hook_tasks", cleanUnlinkedWebhookAndHookTasks),
// v19 -> v20:v0.13.0
NewMigration("migrate access tokens to store SHA56", migrateAccessTokenToSHA256),
// v20 -> v21:v0.13.0
NewMigration("add index to action.user_id", addIndexToActionUserID),
// v21 -> v22:v0.13.0
//
// NOTE: There was a bug in calculating the value of the `version.version`
// column after a migration is done, thus some instances are on v21 but some are
// on v22. Let's make a noop v22 to make sure every instance will not miss a
// real future migration.
NewMigration("noop", func(*gorm.DB) error { return nil }),
}
var errMigrationSkipped = errors.New("the migration has been skipped")
// Migrate migrates the database schema and/or data to the current version.
func Migrate(db *gorm.DB) error {
// NOTE: GORM has problem migrating tables that happen to have columns with the
// same name, see https://github.com/gogs/gogs/issues/7056.
if !db.Migrator().HasTable(new(Version)) {
err := db.AutoMigrate(new(Version))
if err != nil {
return errors.Wrap(err, `auto migrate "version" table`)
}
}
var current Version
err := db.Where("id = ?", 1).First(¤t).Error
if err == gorm.ErrRecordNotFound {
err = db.Create(
&Version{
ID: 1,
Version: int64(minDBVersion + len(migrations)),
},
).Error
if err != nil {
return errors.Wrap(err, "create the version record")
}
return nil
} else if err != nil {
return errors.Wrap(err, "get the version record")
}
if minDBVersion > current.Version {
log.Fatal(`
Hi there, thank you for using Gogs for so long!
However, Gogs has stopped supporting auto-migration from your previously installed version.
But the good news is, it's very easy to fix this problem!
You can migrate your older database using a previous release, then you can upgrade to the newest version.
Please save following instructions to somewhere and start working:
- If you were using below 0.6.0 (e.g. 0.5.x), download last supported archive from following link:
https://gogs.io/gogs/releases/tag/v0.7.33
- If you were using below 0.7.0 (e.g. 0.6.x), download last supported archive from following link:
https://gogs.io/gogs/releases/tag/v0.9.141
- If you were using below 0.11.55 (e.g. 0.9.141), download last supported archive from following link:
https://gogs.io/gogs/releases/tag/v0.12.0
Once finished downloading:
1. Extract the archive and to upgrade steps as usual.
2. Run it once. To verify, you should see some migration traces.
3. Once it starts web server successfully, stop it.
4. Now it's time to put back the release archive you originally intent to upgrade.
5. Enjoy!
In case you're stilling getting this notice, go through instructions again until it disappears.`)
return nil
}
if int(current.Version-minDBVersion) > len(migrations) {
// User downgraded Gogs.
current.Version = int64(len(migrations) + minDBVersion)
return db.Where("id = ?", current.ID).Updates(current).Error
}
for _, m := range migrations[current.Version-minDBVersion:] {
log.Info("Migration: %s", m.Description())
if err = m.Migrate(db); err != nil {
if err != errMigrationSkipped {
return errors.Wrap(err, "do migrate")
}
log.Trace("The migration %q has been skipped", m.Description())
}
current.Version++
err = db.Where("id = ?", current.ID).Updates(current).Error
if err != nil {
return errors.Wrap(err, "update the version record")
}
}
return nil
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/migrations/main_test.go | internal/database/migrations/main_test.go | // Copyright 2022 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package migrations
import (
"flag"
"fmt"
"os"
"testing"
"gorm.io/gorm/logger"
_ "modernc.org/sqlite"
log "unknwon.dev/clog/v2"
"gogs.io/gogs/internal/testutil"
)
func TestMain(m *testing.M) {
flag.Parse()
level := logger.Silent
if !testing.Verbose() {
// Remove the primary logger and register a noop logger.
log.Remove(log.DefaultConsoleName)
err := log.New("noop", testutil.InitNoopLogger)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
} else {
level = logger.Info
}
// NOTE: AutoMigrate does not respect logger passed in gorm.Config.
logger.Default = logger.Default.LogMode(level)
os.Exit(m.Run())
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/migrations/v20_test.go | internal/database/migrations/v20_test.go | // Copyright 2022 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package migrations
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gogs.io/gogs/internal/dbtest"
)
type accessTokenPreV20 struct {
ID int64
UserID int64 `gorm:"COLUMN:uid;INDEX"`
Name string
Sha1 string `gorm:"TYPE:VARCHAR(40);UNIQUE"`
CreatedUnix int64
UpdatedUnix int64
}
func (*accessTokenPreV20) TableName() string {
return "access_token"
}
type accessTokenV20 struct {
ID int64
UserID int64 `gorm:"column:uid;index"`
Name string
Sha1 string `gorm:"type:VARCHAR(40);unique"`
SHA256 string `gorm:"type:VARCHAR(64);unique;not null"`
CreatedUnix int64
UpdatedUnix int64
}
func (*accessTokenV20) TableName() string {
return "access_token"
}
func TestMigrateAccessTokenToSHA256(t *testing.T) {
if testing.Short() {
t.Skip()
}
t.Parallel()
db := dbtest.NewDB(t, "migrateAccessTokenToSHA256", new(accessTokenPreV20))
err := db.Create(
&accessTokenPreV20{
ID: 1,
UserID: 1,
Name: "test",
Sha1: "73da7bb9d2a475bbc2ab79da7d4e94940cb9f9d5",
CreatedUnix: db.NowFunc().Unix(),
UpdatedUnix: db.NowFunc().Unix(),
},
).Error
require.NoError(t, err)
err = migrateAccessTokenToSHA256(db)
require.NoError(t, err)
var got accessTokenV20
err = db.Where("id = ?", 1).First(&got).Error
require.NoError(t, err)
assert.Equal(t, "73da7bb9d2a475bbc2ab79da7d4e94940cb9f9d5", got.Sha1)
assert.Equal(t, "ab144c7bd170691bb9bb995f1541c608e33a78b40174f30fc8a1616c0bc3a477", got.SHA256)
// Re-run should be skipped
err = migrateAccessTokenToSHA256(db)
require.Equal(t, errMigrationSkipped, err)
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/migrations/v21.go | internal/database/migrations/v21.go | // Copyright 2022 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package migrations
import (
"gorm.io/gorm"
)
func addIndexToActionUserID(db *gorm.DB) error {
type action struct {
UserID string `gorm:"index"`
}
if db.Migrator().HasIndex(&action{}, "UserID") {
return errMigrationSkipped
}
return db.Migrator().CreateIndex(&action{}, "UserID")
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/schemadoc/main.go | internal/database/schemadoc/main.go | package main
import (
"fmt"
"log"
"os"
"sort"
"strings"
"github.com/olekukonko/tablewriter"
"github.com/pkg/errors"
"gopkg.in/DATA-DOG/go-sqlmock.v2"
"gorm.io/driver/mysql"
"gorm.io/driver/postgres"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"gorm.io/gorm/schema"
"gogs.io/gogs/internal/database"
)
//go:generate go run main.go ../../../docs/dev/database_schema.md
func main() {
w, err := os.Create(os.Args[1])
if err != nil {
log.Fatalf("Failed to create file: %v", err)
}
defer func() { _ = w.Close() }()
conn, _, err := sqlmock.New()
if err != nil {
log.Fatalf("Failed to get mock connection: %v", err)
}
defer func() { _ = conn.Close() }()
dialectors := []gorm.Dialector{
postgres.New(postgres.Config{
Conn: conn,
}),
mysql.New(mysql.Config{
Conn: conn,
SkipInitializeWithVersion: true,
}),
sqlite.Open(""),
}
collected := make([][]*tableInfo, 0, len(dialectors))
for i, dialector := range dialectors {
tableInfos, err := generate(dialector)
if err != nil {
log.Fatalf("Failed to get table info of %d: %v", i, err)
}
collected = append(collected, tableInfos)
}
for i, ti := range collected[0] {
_, _ = w.WriteString(`# Table "` + ti.Name + `"`)
_, _ = w.WriteString("\n\n")
_, _ = w.WriteString("```\n")
table := tablewriter.NewWriter(w)
table.SetHeader([]string{"Field", "Column", "PostgreSQL", "MySQL", "SQLite3"})
table.SetBorder(false)
for j, f := range ti.Fields {
table.Append([]string{
f.Name, f.Column,
strings.ToUpper(f.Type), // PostgreSQL
strings.ToUpper(collected[1][i].Fields[j].Type), // MySQL
strings.ToUpper(collected[2][i].Fields[j].Type), // SQLite3
})
}
table.Render()
_, _ = w.WriteString("\n")
_, _ = w.WriteString("Primary keys: ")
_, _ = w.WriteString(strings.Join(ti.PrimaryKeys, ", "))
_, _ = w.WriteString("\n")
if len(ti.Indexes) > 0 {
_, _ = w.WriteString("Indexes: \n")
for _, index := range ti.Indexes {
_, _ = fmt.Fprintf(w, "\t%q", index.Name)
if index.Class != "" {
_, _ = fmt.Fprintf(w, " %s", index.Class)
}
if index.Type != "" {
_, _ = fmt.Fprintf(w, ", %s", index.Type)
}
if len(index.Fields) > 0 {
fields := make([]string, len(index.Fields))
for i := range index.Fields {
fields[i] = index.Fields[i].DBName
}
_, _ = fmt.Fprintf(w, " (%s)", strings.Join(fields, ", "))
}
_, _ = w.WriteString("\n")
}
}
_, _ = w.WriteString("```\n\n")
}
}
type tableField struct {
Name string
Column string
Type string
}
type tableInfo struct {
Name string
Fields []*tableField
PrimaryKeys []string
Indexes []schema.Index
}
// This function is derived from gorm.io/gorm/migrator/migrator.go:Migrator.CreateTable.
func generate(dialector gorm.Dialector) ([]*tableInfo, error) {
conn, err := gorm.Open(dialector,
&gorm.Config{
SkipDefaultTransaction: true,
NamingStrategy: schema.NamingStrategy{
SingularTable: true,
},
DryRun: true,
DisableAutomaticPing: true,
},
)
if err != nil {
return nil, errors.Wrap(err, "open database")
}
m := conn.Migrator().(interface {
RunWithValue(value any, fc func(*gorm.Statement) error) error
FullDataTypeOf(*schema.Field) clause.Expr
})
tableInfos := make([]*tableInfo, 0, len(database.Tables))
for _, table := range database.Tables {
err = m.RunWithValue(table, func(stmt *gorm.Statement) error {
fields := make([]*tableField, 0, len(stmt.Schema.DBNames))
for _, field := range stmt.Schema.Fields {
if field.DBName == "" {
continue
}
tags := make([]string, 0)
for tag := range field.TagSettings {
if tag == "UNIQUE" {
tags = append(tags, tag)
}
}
typeSuffix := ""
if len(tags) > 0 {
typeSuffix = " " + strings.Join(tags, " ")
}
fields = append(fields, &tableField{
Name: field.Name,
Column: field.DBName,
Type: m.FullDataTypeOf(field).SQL + typeSuffix,
})
}
primaryKeys := make([]string, 0, len(stmt.Schema.PrimaryFields))
if len(stmt.Schema.PrimaryFields) > 0 {
for _, field := range stmt.Schema.PrimaryFields {
primaryKeys = append(primaryKeys, field.DBName)
}
}
var indexes []schema.Index
for _, index := range stmt.Schema.ParseIndexes() {
indexes = append(indexes, index)
}
sort.Slice(indexes, func(i, j int) bool {
return indexes[i].Name < indexes[j].Name
})
tableInfos = append(tableInfos, &tableInfo{
Name: stmt.Table,
Fields: fields,
PrimaryKeys: primaryKeys,
Indexes: indexes,
})
return nil
})
if err != nil {
return nil, errors.Wrap(err, "gather table information")
}
}
return tableInfos, nil
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/testutil/exec.go | internal/testutil/exec.go | // Copyright 2020 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package testutil
import (
"errors"
"fmt"
"os"
"os/exec"
"strings"
)
// Exec executes "go test" on given helper with supplied environment variables.
// It is useful to mock "os/exec" functions in tests. When succeeded, it returns
// the result produced by the test helper.
// The test helper should:
// 1. Use WantHelperProcess function to determine if it is being called in helper mode.
// 2. Call fmt.Fprintln(os.Stdout, ...) to print results for the main test to collect.
func Exec(helper string, envs ...string) (string, error) {
cmd := exec.Command(os.Args[0], "-test.run="+helper, "--")
cmd.Env = []string{
"GO_WANT_HELPER_PROCESS=1",
"GOCOVERDIR=" + os.TempDir(),
}
cmd.Env = append(cmd.Env, envs...)
out, err := cmd.CombinedOutput()
str := string(out)
// The error is quite confusing even when tests passed, so let's check whether
// it is passed first.
if strings.Contains(str, "no tests to run") {
return "", errors.New("no tests to run")
} else if i := strings.Index(str, "PASS"); i >= 0 {
// Collect helper result
return strings.TrimSpace(str[:i]), nil
}
if err != nil {
return "", fmt.Errorf("%v - %s", err, str)
}
return "", errors.New(str)
}
// WantHelperProcess returns true if current process is in helper mode.
func WantHelperProcess() bool {
return os.Getenv("GO_WANT_HELPER_PROCESS") == "1"
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/testutil/golden.go | internal/testutil/golden.go | // Copyright 2020 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package testutil
import (
"encoding/json"
"flag"
"os"
"path/filepath"
"regexp"
"runtime"
"testing"
"github.com/stretchr/testify/assert"
)
var updateRegex = flag.String("update", "", "Update testdata of tests matching the given regex")
// Update returns true if update regex matches given test name.
func Update(name string) bool {
if updateRegex == nil || *updateRegex == "" {
return false
}
return regexp.MustCompile(*updateRegex).MatchString(name)
}
// AssertGolden compares what's got and what's in the golden file. It updates
// the golden file on-demand. It does nothing when the runtime is "windows".
func AssertGolden(t testing.TB, path string, update bool, got any) {
if runtime.GOOS == "windows" {
t.Skip("Skipping testing on Windows")
return
}
t.Helper()
data := marshal(t, got)
if update {
err := os.MkdirAll(filepath.Dir(path), os.ModePerm)
if err != nil {
t.Fatalf("create directories for golden file %q: %v", path, err)
}
err = os.WriteFile(path, data, 0640)
if err != nil {
t.Fatalf("update golden file %q: %v", path, err)
}
}
golden, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read golden file %q: %v", path, err)
}
assert.Equal(t, string(golden), string(data))
}
func marshal(t testing.TB, v any) []byte {
t.Helper()
switch v2 := v.(type) {
case string:
return []byte(v2)
case []byte:
return v2
default:
data, err := json.MarshalIndent(v, "", " ")
if err != nil {
t.Fatal(err)
}
return data
}
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/testutil/testutil_test.go | internal/testutil/testutil_test.go | // Copyright 2022 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package testutil
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestInTest(t *testing.T) {
assert.True(t, InTest)
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/testutil/exec_test.go | internal/testutil/exec_test.go | // Copyright 2020 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package testutil
import (
"errors"
"fmt"
"os"
"testing"
"github.com/stretchr/testify/assert"
)
func TestExecHelper(_ *testing.T) {
if !WantHelperProcess() {
return
}
if os.Getenv("PASS") != "1" {
fmt.Fprintln(os.Stdout, "tests failed")
os.Exit(1)
}
fmt.Fprintln(os.Stdout, "tests succeed")
}
func TestExec(t *testing.T) {
tests := []struct {
helper string
env string
expOut string
expErr error
}{
{
helper: "NoTestsToRun",
expErr: errors.New("no tests to run"),
}, {
helper: "TestExecHelper",
expErr: errors.New("exit status 1 - tests failed\n"),
}, {
helper: "TestExecHelper",
env: "PASS=1",
expOut: "tests succeed",
},
}
for _, test := range tests {
t.Run("", func(t *testing.T) {
out, err := Exec(test.helper, test.env)
assert.Equal(t, test.expErr, err)
assert.Equal(t, test.expOut, out)
})
}
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/testutil/noop_logger.go | internal/testutil/noop_logger.go | // Copyright 2020 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package testutil
import (
log "unknwon.dev/clog/v2"
)
var _ log.Logger = (*noopLogger)(nil)
// noopLogger is a placeholder logger that logs nothing.
type noopLogger struct{}
func (*noopLogger) Name() string {
return "noop"
}
func (*noopLogger) Level() log.Level {
return log.LevelTrace
}
func (*noopLogger) Write(log.Messager) error {
return nil
}
// InitNoopLogger is a init function to initialize a noop logger.
var InitNoopLogger = func(name string, vs ...any) (log.Logger, error) {
return &noopLogger{}, nil
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/testutil/golden_test.go | internal/testutil/golden_test.go | // Copyright 2020 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package testutil
import (
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
)
func TestUpdate(t *testing.T) {
before := updateRegex
defer func() {
updateRegex = before
}()
t.Run("no flag", func(t *testing.T) {
updateRegex = nil
assert.False(t, Update("TestUpdate"))
})
tests := []struct {
regex string
name string
want bool
}{
{regex: "", name: "TestUpdate", want: false},
{regex: "TestNotFound", name: "TestUpdate", want: false},
{regex: ".*", name: "TestUpdate", want: true},
}
for _, test := range tests {
t.Run("", func(t *testing.T) {
updateRegex = &test.regex
assert.Equal(t, test.want, Update(test.name))
})
}
}
func TestAssertGolden(t *testing.T) {
// Make sure it does not blow up
AssertGolden(t, filepath.Join("testdata", "golden"), false, "{\n \"Message\": \"This is a golden file.\"\n}")
AssertGolden(t, filepath.Join("testdata", "golden"), false, []byte("{\n \"Message\": \"This is a golden file.\"\n}"))
type T struct {
Message string
}
AssertGolden(t, filepath.Join("testdata", "golden"), false, T{"This is a golden file."})
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/testutil/testutil.go | internal/testutil/testutil.go | // Copyright 2022 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package testutil
import (
"os"
"strings"
)
// InTest is ture if the current binary looks like a test artifact.
var InTest = len(os.Args) > 0 && strings.HasSuffix(strings.TrimSuffix(os.Args[0], ".exe"), ".test")
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/form/form.go | internal/form/form.go | // Copyright 2017 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package form
import (
"fmt"
"reflect"
"strings"
"github.com/go-macaron/binding"
"github.com/unknwon/com"
"gopkg.in/macaron.v1"
"gogs.io/gogs/internal/lazyregexp"
)
const ErrAlphaDashDotSlash = "AlphaDashDotSlashError"
var AlphaDashDotSlashPattern = lazyregexp.New("[^\\d\\w-_\\./]")
func init() {
binding.SetNameMapper(com.ToSnakeCase)
binding.AddRule(&binding.Rule{
IsMatch: func(rule string) bool {
return rule == "AlphaDashDotSlash"
},
IsValid: func(errs binding.Errors, name string, v any) (bool, binding.Errors) {
if AlphaDashDotSlashPattern.MatchString(fmt.Sprintf("%v", v)) {
errs.Add([]string{name}, ErrAlphaDashDotSlash, "AlphaDashDotSlash")
return false, errs
}
return true, errs
},
})
}
type Form interface {
binding.Validator
}
// Assign assign form values back to the template data.
func Assign(form any, data map[string]any) {
typ := reflect.TypeOf(form)
val := reflect.ValueOf(form)
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
val = val.Elem()
}
for i := 0; i < typ.NumField(); i++ {
field := typ.Field(i)
fieldName := field.Tag.Get("form")
// Allow ignored fields in the struct
if fieldName == "-" {
continue
} else if fieldName == "" {
fieldName = com.ToSnakeCase(field.Name)
}
data[fieldName] = val.Field(i).Interface()
}
}
func getRuleBody(field reflect.StructField, prefix string) string {
for _, rule := range strings.Split(field.Tag.Get("binding"), ";") {
if strings.HasPrefix(rule, prefix) {
return rule[len(prefix) : len(rule)-1]
}
}
return ""
}
func getSize(field reflect.StructField) string {
return getRuleBody(field, "Size(")
}
func getMinSize(field reflect.StructField) string {
return getRuleBody(field, "MinSize(")
}
func getMaxSize(field reflect.StructField) string {
return getRuleBody(field, "MaxSize(")
}
func getInclude(field reflect.StructField) string {
return getRuleBody(field, "Include(")
}
func validate(errs binding.Errors, data map[string]any, f Form, l macaron.Locale) binding.Errors {
if errs.Len() == 0 {
return errs
}
data["HasError"] = true
Assign(f, data)
typ := reflect.TypeOf(f)
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
for i := 0; i < typ.NumField(); i++ {
field := typ.Field(i)
fieldName := field.Tag.Get("form")
// Allow ignored fields in the struct
if fieldName == "-" {
continue
}
if errs[0].FieldNames[0] == field.Name {
data["Err_"+field.Name] = true
trName := field.Tag.Get("locale")
if trName == "" {
trName = l.Tr("form." + field.Name)
} else {
trName = l.Tr(trName)
}
switch errs[0].Classification {
case binding.ERR_REQUIRED:
data["ErrorMsg"] = trName + l.Tr("form.require_error")
case binding.ERR_ALPHA_DASH:
data["ErrorMsg"] = trName + l.Tr("form.alpha_dash_error")
case binding.ERR_ALPHA_DASH_DOT:
data["ErrorMsg"] = trName + l.Tr("form.alpha_dash_dot_error")
case ErrAlphaDashDotSlash:
data["ErrorMsg"] = trName + l.Tr("form.alpha_dash_dot_slash_error")
case binding.ERR_SIZE:
data["ErrorMsg"] = trName + l.Tr("form.size_error", getSize(field))
case binding.ERR_MIN_SIZE:
data["ErrorMsg"] = trName + l.Tr("form.min_size_error", getMinSize(field))
case binding.ERR_MAX_SIZE:
data["ErrorMsg"] = trName + l.Tr("form.max_size_error", getMaxSize(field))
case binding.ERR_EMAIL:
data["ErrorMsg"] = trName + l.Tr("form.email_error")
case binding.ERR_URL:
data["ErrorMsg"] = trName + l.Tr("form.url_error")
case binding.ERR_INCLUDE:
data["ErrorMsg"] = trName + l.Tr("form.include_error", getInclude(field))
default:
data["ErrorMsg"] = l.Tr("form.unknown_error") + " " + errs[0].Classification
}
return errs
}
}
return errs
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/form/admin.go | internal/form/admin.go | // Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package form
import (
"github.com/go-macaron/binding"
"gopkg.in/macaron.v1"
)
type AdminCrateUser struct {
LoginType string `binding:"Required"`
LoginName string
UserName string `binding:"Required;AlphaDashDot;MaxSize(35)"`
Email string `binding:"Required;Email;MaxSize(254)"`
Password string `binding:"MaxSize(255)"`
SendNotify bool
}
func (f *AdminCrateUser) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
type AdminEditUser struct {
LoginType string `binding:"Required"`
LoginName string
FullName string `binding:"MaxSize(100)"`
Email string `binding:"Required;Email;MaxSize(254)"`
Password string `binding:"MaxSize(255)"`
Website string `binding:"MaxSize(50)"`
Location string `binding:"MaxSize(50)"`
MaxRepoCreation int
Active bool
Admin bool
AllowGitHook bool
AllowImportLocal bool
ProhibitLogin bool
}
func (f *AdminEditUser) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/form/repo.go | internal/form/repo.go | // Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package form
import (
"net/url"
"strings"
"github.com/go-macaron/binding"
"github.com/unknwon/com"
"gopkg.in/macaron.v1"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/database"
"gogs.io/gogs/internal/netutil"
)
// _______________________________________ _________.______________________ _______________.___.
// \______ \_ _____/\______ \_____ \ / _____/| \__ ___/\_____ \\______ \__ | |
// | _/| __)_ | ___// | \ \_____ \ | | | | / | \| _// | |
// | | \| \ | | / | \/ \| | | | / | \ | \\____ |
// |____|_ /_______ / |____| \_______ /_______ /|___| |____| \_______ /____|_ // ______|
// \/ \/ \/ \/ \/ \/ \/
type CreateRepo struct {
UserID int64 `binding:"Required"`
RepoName string `binding:"Required;AlphaDashDot;MaxSize(100)"`
Private bool
Unlisted bool
Description string `binding:"MaxSize(512)"`
AutoInit bool
Gitignores string
License string
Readme string
}
func (f *CreateRepo) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
type MigrateRepo struct {
CloneAddr string `json:"clone_addr" binding:"Required"`
AuthUsername string `json:"auth_username"`
AuthPassword string `json:"auth_password"`
UID int64 `json:"uid" binding:"Required"`
RepoName string `json:"repo_name" binding:"Required;AlphaDashDot;MaxSize(100)"`
Mirror bool `json:"mirror"`
Private bool `json:"private"`
Unlisted bool `json:"unlisted"`
Description string `json:"description" binding:"MaxSize(512)"`
}
func (f *MigrateRepo) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
// ParseRemoteAddr checks if given remote address is valid,
// and returns composed URL with needed username and password.
// It also checks if given user has permission when remote address
// is actually a local path.
func (f MigrateRepo) ParseRemoteAddr(user *database.User) (string, error) {
remoteAddr := strings.TrimSpace(f.CloneAddr)
// Remote address can be HTTP/HTTPS/Git URL or local path.
if strings.HasPrefix(remoteAddr, "http://") ||
strings.HasPrefix(remoteAddr, "https://") ||
strings.HasPrefix(remoteAddr, "git://") {
u, err := url.Parse(remoteAddr)
if err != nil {
return "", database.ErrInvalidCloneAddr{IsURLError: true}
}
if netutil.IsBlockedLocalHostname(u.Hostname(), conf.Security.LocalNetworkAllowlist) {
return "", database.ErrInvalidCloneAddr{IsBlockedLocalAddress: true}
}
if len(f.AuthUsername)+len(f.AuthPassword) > 0 {
u.User = url.UserPassword(f.AuthUsername, f.AuthPassword)
}
// To prevent CRLF injection in git protocol, see https://github.com/gogs/gogs/issues/6413
if u.Scheme == "git" && (strings.Contains(remoteAddr, "%0d") || strings.Contains(remoteAddr, "%0a")) {
return "", database.ErrInvalidCloneAddr{IsURLError: true}
}
remoteAddr = u.String()
} else if !user.CanImportLocal() {
return "", database.ErrInvalidCloneAddr{IsPermissionDenied: true}
} else if !com.IsDir(remoteAddr) {
return "", database.ErrInvalidCloneAddr{IsInvalidPath: true}
}
return remoteAddr, nil
}
type RepoSetting struct {
RepoName string `binding:"Required;AlphaDashDot;MaxSize(100)"`
Description string `binding:"MaxSize(512)"`
Website string `binding:"Url;MaxSize(100)"`
Branch string
Interval int
MirrorAddress string
Private bool
Unlisted bool
EnablePrune bool
// Advanced settings
EnableWiki bool
AllowPublicWiki bool
EnableExternalWiki bool
ExternalWikiURL string
EnableIssues bool
AllowPublicIssues bool
EnableExternalTracker bool
ExternalTrackerURL string
TrackerURLFormat string
TrackerIssueStyle string
EnablePulls bool
PullsIgnoreWhitespace bool
PullsAllowRebase bool
}
func (f *RepoSetting) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
// __________ .__
// \______ \____________ ____ ____ | |__
// | | _/\_ __ \__ \ / \_/ ___\| | \
// | | \ | | \// __ \| | \ \___| Y \
// |______ / |__| (____ /___| /\___ >___| /
// \/ \/ \/ \/ \/
type ProtectBranch struct {
Protected bool
RequirePullRequest bool
EnableWhitelist bool
WhitelistUsers string
WhitelistTeams string
}
func (f *ProtectBranch) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
// __ __ ___. .__ .__ __
// / \ / \ ____\_ |__ | |__ | |__ ____ | | __
// \ \/\/ // __ \| __ \| | \| | \ / _ \| |/ /
// \ /\ ___/| \_\ \ Y \ Y ( <_> ) <
// \__/\ / \___ >___ /___| /___| /\____/|__|_ \
// \/ \/ \/ \/ \/ \/
type Webhook struct {
Events string
Create bool
Delete bool
Fork bool
Push bool
Issues bool
IssueComment bool
PullRequest bool
Release bool
Active bool
}
func (f Webhook) PushOnly() bool {
return f.Events == "push_only"
}
func (f Webhook) SendEverything() bool {
return f.Events == "send_everything"
}
func (f Webhook) ChooseEvents() bool {
return f.Events == "choose_events"
}
type NewWebhook struct {
PayloadURL string `binding:"Required;Url"`
ContentType int `binding:"Required"`
Secret string
Webhook
}
func (f *NewWebhook) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
type NewSlackHook struct {
PayloadURL string `binding:"Required;Url"`
Channel string `binding:"Required"`
Username string
IconURL string
Color string
Webhook
}
func (f *NewSlackHook) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
type NewDiscordHook struct {
PayloadURL string `binding:"Required;Url"`
Username string
IconURL string
Color string
Webhook
}
func (f *NewDiscordHook) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
type NewDingtalkHook struct {
PayloadURL string `binding:"Required;Url"`
Webhook
}
func (f *NewDingtalkHook) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
// .___
// | | ______ ________ __ ____
// | |/ ___// ___/ | \_/ __ \
// | |\___ \ \___ \| | /\ ___/
// |___/____ >____ >____/ \___ >
// \/ \/ \/
type NewIssue struct {
Title string `binding:"Required;MaxSize(255)"`
LabelIDs string `form:"label_ids"`
MilestoneID int64
AssigneeID int64
Content string
Files []string
}
func (f *NewIssue) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
type CreateComment struct {
Content string
Status string `binding:"OmitEmpty;In(reopen,close)"`
Files []string
}
func (f *CreateComment) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
// _____ .__.__ __
// / \ |__| | ____ _______/ |_ ____ ____ ____
// / \ / \| | | _/ __ \ / ___/\ __\/ _ \ / \_/ __ \
// / Y \ | |_\ ___/ \___ \ | | ( <_> ) | \ ___/
// \____|__ /__|____/\___ >____ > |__| \____/|___| /\___ >
// \/ \/ \/ \/ \/
type CreateMilestone struct {
Title string `binding:"Required;MaxSize(50)"`
Content string
Deadline string
}
func (f *CreateMilestone) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
// .____ ___. .__
// | | _____ \_ |__ ____ | |
// | | \__ \ | __ \_/ __ \| |
// | |___ / __ \| \_\ \ ___/| |__
// |_______ (____ /___ /\___ >____/
// \/ \/ \/ \/
type CreateLabel struct {
ID int64
Title string `binding:"Required;MaxSize(50)" locale:"repo.issues.label_title"`
Color string `binding:"Required;Size(7)" locale:"repo.issues.label_color"`
}
func (f *CreateLabel) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
type InitializeLabels struct {
TemplateName string `binding:"Required"`
}
func (f *InitializeLabels) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
// __________ .__
// \______ \ ____ | | ____ _____ ______ ____
// | _// __ \| | _/ __ \\__ \ / ___// __ \
// | | \ ___/| |_\ ___/ / __ \_\___ \\ ___/
// |____|_ /\___ >____/\___ >____ /____ >\___ >
// \/ \/ \/ \/ \/ \/
type NewRelease struct {
TagName string `binding:"Required"`
Target string `form:"tag_target" binding:"Required"`
Title string `binding:"Required"`
Content string
Draft string
Prerelease bool
Files []string
}
func (f *NewRelease) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
type EditRelease struct {
Title string `binding:"Required"`
Content string
Draft string
Prerelease bool
Files []string
}
func (f *EditRelease) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
// __ __.__ __ .__
// / \ / \__| | _|__|
// \ \/\/ / | |/ / |
// \ /| | <| |
// \__/\ / |__|__|_ \__|
// \/ \/
type NewWiki struct {
OldTitle string
Title string `binding:"Required"`
Content string `binding:"Required"`
Message string
}
// FIXME: use code generation to generate this method.
func (f *NewWiki) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
// ___________ .___.__ __
// \_ _____/ __| _/|__|/ |_
// | __)_ / __ | | \ __\
// | \/ /_/ | | || |
// /_______ /\____ | |__||__|
// \/ \/
type EditRepoFile struct {
TreePath string `binding:"Required;MaxSize(500)"`
Content string `binding:"Required"`
CommitSummary string `binding:"MaxSize(100)"`
CommitMessage string
CommitChoice string `binding:"Required;MaxSize(50)"`
NewBranchName string `binding:"AlphaDashDotSlash;MaxSize(100)"`
LastCommit string
}
func (f *EditRepoFile) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
func (f *EditRepoFile) IsNewBrnach() bool {
return f.CommitChoice == "commit-to-new-branch"
}
type EditPreviewDiff struct {
Content string
}
func (f *EditPreviewDiff) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
// ____ ___ .__ .___
// | | \______ | | _________ __| _/
// | | /\____ \| | / _ \__ \ / __ |
// | | / | |_> > |_( <_> ) __ \_/ /_/ |
// |______/ | __/|____/\____(____ /\____ |
// |__| \/ \/
//
type UploadRepoFile struct {
TreePath string `binding:"MaxSize(500)"`
CommitSummary string `binding:"MaxSize(100)"`
CommitMessage string
CommitChoice string `binding:"Required;MaxSize(50)"`
NewBranchName string `binding:"AlphaDashDot;MaxSize(100)"`
Files []string
}
func (f *UploadRepoFile) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
func (f *UploadRepoFile) IsNewBrnach() bool {
return f.CommitChoice == "commit-to-new-branch"
}
type RemoveUploadFile struct {
File string `binding:"Required;MaxSize(50)"`
}
func (f *RemoveUploadFile) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
// ________ .__ __
// \______ \ ____ | | _____/ |_ ____
// | | \_/ __ \| | _/ __ \ __\/ __ \
// | ` \ ___/| |_\ ___/| | \ ___/
// /_______ /\___ >____/\___ >__| \___ >
// \/ \/ \/ \/
type DeleteRepoFile struct {
CommitSummary string `binding:"MaxSize(100)"`
CommitMessage string
CommitChoice string `binding:"Required;MaxSize(50)"`
NewBranchName string `binding:"AlphaDashDot;MaxSize(100)"`
}
func (f *DeleteRepoFile) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
func (f *DeleteRepoFile) IsNewBrnach() bool {
return f.CommitChoice == "commit-to-new-branch"
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/form/auth.go | internal/form/auth.go | // Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package form
import (
"github.com/go-macaron/binding"
"gopkg.in/macaron.v1"
)
type Authentication struct {
ID int64
Type int `binding:"Range(2,6)"`
Name string `binding:"Required;MaxSize(30)"`
Host string
Port int
BindDN string
BindPassword string
UserBase string
UserDN string
AttributeUsername string
AttributeName string
AttributeSurname string
AttributeMail string
AttributesInBind bool
Filter string
AdminFilter string
GroupEnabled bool
GroupDN string
GroupFilter string
GroupMemberUID string
UserUID string
IsActive bool
IsDefault bool
SMTPAuth string
SMTPHost string
SMTPPort int
AllowedDomains string
SecurityProtocol int `binding:"Range(0,2)"`
TLS bool
SkipVerify bool
PAMServiceName string
GitHubAPIEndpoint string `form:"github_api_endpoint" binding:"Url"`
}
func (f *Authentication) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/form/user.go | internal/form/user.go | // Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package form
import (
"mime/multipart"
"github.com/go-macaron/binding"
"gopkg.in/macaron.v1"
)
//nolint:staticcheck // Reason: needed for legacy code
type Install struct {
DbType string `binding:"Required"`
DbHost string
DbUser string
DbPasswd string
DbName string
DbSchema string
SSLMode string
DbPath string
AppName string `binding:"Required" locale:"install.app_name"`
RepoRootPath string `binding:"Required"`
RunUser string `binding:"Required"`
Domain string `binding:"Required"`
SSHPort int
UseBuiltinSSHServer bool
HTTPPort string `binding:"Required"`
AppUrl string `binding:"Required"`
LogRootPath string `binding:"Required"`
EnableConsoleMode bool
DefaultBranch string
SMTPHost string
SMTPFrom string
SMTPUser string `binding:"OmitEmpty;MaxSize(254)" locale:"install.mailer_user"`
SMTPPasswd string
RegisterConfirm bool
MailNotify bool
OfflineMode bool
DisableGravatar bool
EnableFederatedAvatar bool
DisableRegistration bool
EnableCaptcha bool
RequireSignInView bool
AdminName string `binding:"OmitEmpty;AlphaDashDot;MaxSize(30)" locale:"install.admin_name"`
AdminPasswd string `binding:"OmitEmpty;MaxSize(255)" locale:"install.admin_password"`
AdminConfirmPasswd string
AdminEmail string `binding:"OmitEmpty;MinSize(3);MaxSize(254);Include(@)" locale:"install.admin_email"`
}
func (f *Install) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
// _____ ____ _________________ ___
// / _ \ | | \__ ___/ | \
// / /_\ \| | / | | / ~ \
// / | \ | / | | \ Y /
// \____|__ /______/ |____| \___|_ /
// \/ \/
type Register struct {
UserName string `binding:"Required;AlphaDashDot;MaxSize(35)"`
Email string `binding:"Required;Email;MaxSize(254)"`
Password string `binding:"Required;MaxSize(255)"`
Retype string
}
func (f *Register) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
type SignIn struct {
UserName string `binding:"Required;MaxSize(254)"`
Password string `binding:"Required;MaxSize(255)"`
LoginSource int64
Remember bool
}
func (f *SignIn) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
// __________________________________________.___ _______ ________ _________
// / _____/\_ _____/\__ ___/\__ ___/| |\ \ / _____/ / _____/
// \_____ \ | __)_ | | | | | |/ | \/ \ ___ \_____ \
// / \ | \ | | | | | / | \ \_\ \/ \
// /_______ //_______ / |____| |____| |___\____|__ /\______ /_______ /
// \/ \/ \/ \/ \/
type UpdateProfile struct {
Name string `binding:"Required;AlphaDashDot;MaxSize(35)"`
FullName string `binding:"MaxSize(100)"`
Website string `binding:"Url;MaxSize(100)"`
Location string `binding:"MaxSize(50)"`
}
func (f *UpdateProfile) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
const (
AvatarLocal string = "local"
AvatarLookup string = "lookup"
)
type Avatar struct {
Source string
Avatar *multipart.FileHeader
Gravatar string `binding:"OmitEmpty;Email;MaxSize(254)"`
Federavatar bool
}
func (f *Avatar) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
type AddEmail struct {
Email string `binding:"Required;Email;MaxSize(254)"`
}
func (f *AddEmail) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
type ChangePassword struct {
OldPassword string `binding:"Required;MinSize(1);MaxSize(255)"`
Password string `binding:"Required;MaxSize(255)"`
Retype string
}
func (f *ChangePassword) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
type AddSSHKey struct {
Title string `binding:"Required;MaxSize(50)"`
Content string `binding:"Required"`
}
func (f *AddSSHKey) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
type NewAccessToken struct {
Name string `binding:"Required"`
}
func (f *NewAccessToken) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/form/org.go | internal/form/org.go | // Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package form
import (
"github.com/go-macaron/binding"
"gopkg.in/macaron.v1"
)
type CreateOrg struct {
OrgName string `binding:"Required;AlphaDashDot;MaxSize(35)" locale:"org.org_name_holder"`
}
func (f *CreateOrg) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
type UpdateOrgSetting struct {
Name string `binding:"Required;AlphaDashDot;MaxSize(35)" locale:"org.org_name_holder"`
FullName string `binding:"MaxSize(100)"`
Description string `binding:"MaxSize(255)"`
Website string `binding:"Url;MaxSize(100)"`
Location string `binding:"MaxSize(50)"`
MaxRepoCreation int
}
func (f *UpdateOrgSetting) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
type CreateTeam struct {
TeamName string `binding:"Required;AlphaDashDot;MaxSize(30)"`
Description string `binding:"MaxSize(255)"`
Permission string
}
func (f *CreateTeam) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/httplib/httplib.go | internal/httplib/httplib.go | // Copyright 2013 The Beego Authors. All rights reserved.
// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package httplib
import (
"bytes"
"context"
"crypto/tls"
"io"
"log"
"mime/multipart"
"net"
"net/http"
"net/http/cookiejar"
"net/http/httputil"
"net/url"
"os"
"strings"
"sync"
"time"
)
var (
defaultSetting = Settings{false, "GogsServer", 60 * time.Second, 60 * time.Second, nil, nil, nil, false}
defaultCookieJar http.CookieJar
settingMutex sync.Mutex
)
// createDefaultCookie creates a global cookiejar to store cookies.
func createDefaultCookie() {
settingMutex.Lock()
defer settingMutex.Unlock()
defaultCookieJar, _ = cookiejar.New(nil)
}
// Overwrite default settings
func SetDefaultSetting(setting Settings) {
settingMutex.Lock()
defer settingMutex.Unlock()
defaultSetting = setting
if defaultSetting.ConnectTimeout == 0 {
defaultSetting.ConnectTimeout = 60 * time.Second
}
if defaultSetting.ReadWriteTimeout == 0 {
defaultSetting.ReadWriteTimeout = 60 * time.Second
}
}
// return *Request with specific method
func newRequest(url, method string) *Request {
var resp http.Response
req := http.Request{
Method: method,
Header: make(http.Header),
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
}
return &Request{url, &req, map[string]string{}, map[string]string{}, defaultSetting, &resp, nil}
}
// Get returns *Request with GET method.
func Get(url string) *Request {
return newRequest(url, "GET")
}
// Post returns *Request with POST method.
func Post(url string) *Request {
return newRequest(url, "POST")
}
// Put returns *Request with PUT method.
func Put(url string) *Request {
return newRequest(url, "PUT")
}
// Delete returns *Request DELETE method.
func Delete(url string) *Request {
return newRequest(url, "DELETE")
}
// Head returns *Request with HEAD method.
func Head(url string) *Request {
return newRequest(url, "HEAD")
}
type Settings struct {
ShowDebug bool
UserAgent string
ConnectTimeout time.Duration
ReadWriteTimeout time.Duration
TLSClientConfig *tls.Config
Proxy func(*http.Request) (*url.URL, error)
Transport http.RoundTripper
EnableCookie bool
}
// Request provides more useful methods for requesting a URL than http.Request.
type Request struct {
url string
req *http.Request
params map[string]string
files map[string]string
setting Settings
resp *http.Response
body []byte
}
// Setting changes the request settings
func (r *Request) Setting(setting Settings) *Request {
r.setting = setting
return r
}
// SetBasicAuth sets the request's Authorization header to use HTTP Basic Authentication with the provided username and password.
func (r *Request) SetBasicAuth(username, password string) *Request {
r.req.SetBasicAuth(username, password)
return r
}
// SetEnableCookie sets enable/disable cookiejar
func (r *Request) SetEnableCookie(enable bool) *Request {
r.setting.EnableCookie = enable
return r
}
// SetUserAgent sets User-Agent header field
func (r *Request) SetUserAgent(useragent string) *Request {
r.setting.UserAgent = useragent
return r
}
// Debug sets show debug or not when executing request.
func (r *Request) Debug(isdebug bool) *Request {
r.setting.ShowDebug = isdebug
return r
}
// SetTimeout sets connect time out and read-write time out for Request.
func (r *Request) SetTimeout(connectTimeout, readWriteTimeout time.Duration) *Request {
r.setting.ConnectTimeout = connectTimeout
r.setting.ReadWriteTimeout = readWriteTimeout
return r
}
// SetTLSClientConfig sets tls connection configurations if visiting https url.
func (r *Request) SetTLSClientConfig(config *tls.Config) *Request {
r.setting.TLSClientConfig = config
return r
}
// Header add header item string in request.
func (r *Request) Header(key, value string) *Request {
r.req.Header.Set(key, value)
return r
}
func (r *Request) Headers() http.Header {
return r.req.Header
}
// Set the protocol version for incoming requests.
// Client requests always use HTTP/1.1.
func (r *Request) SetProtocolVersion(vers string) *Request {
if vers == "" {
vers = "HTTP/1.1"
}
major, minor, ok := http.ParseHTTPVersion(vers)
if ok {
r.req.Proto = vers
r.req.ProtoMajor = major
r.req.ProtoMinor = minor
}
return r
}
// SetCookie add cookie into request.
func (r *Request) SetCookie(cookie *http.Cookie) *Request {
r.req.Header.Add("Cookie", cookie.String())
return r
}
// Set transport to
func (r *Request) SetTransport(transport http.RoundTripper) *Request {
r.setting.Transport = transport
return r
}
// Set http proxy
// example:
//
// func(req *http.Request) (*url.URL, error) {
// u, _ := url.ParseRequestURI("http://127.0.0.1:8118")
// return u, nil
// }
func (r *Request) SetProxy(proxy func(*http.Request) (*url.URL, error)) *Request {
r.setting.Proxy = proxy
return r
}
// Param adds query param in to request.
// params build query string as ?key1=value1&key2=value2...
func (r *Request) Param(key, value string) *Request {
r.params[key] = value
return r
}
func (r *Request) PostFile(formname, filename string) *Request {
r.files[formname] = filename
return r
}
// Body adds request raw body.
// it supports string and []byte.
func (r *Request) Body(data any) *Request {
switch t := data.(type) {
case string:
bf := bytes.NewBufferString(t)
r.req.Body = io.NopCloser(bf)
r.req.ContentLength = int64(len(t))
case []byte:
bf := bytes.NewBuffer(t)
r.req.Body = io.NopCloser(bf)
r.req.ContentLength = int64(len(t))
}
return r
}
func (r *Request) getResponse() (*http.Response, error) {
if r.resp.StatusCode != 0 {
return r.resp, nil
}
var paramBody string
if len(r.params) > 0 {
var buf bytes.Buffer
for k, v := range r.params {
buf.WriteString(url.QueryEscape(k))
buf.WriteByte('=')
buf.WriteString(url.QueryEscape(v))
buf.WriteByte('&')
}
paramBody = buf.String()
paramBody = paramBody[0 : len(paramBody)-1]
}
if r.req.Method == "GET" && len(paramBody) > 0 {
if strings.Contains(r.url, "?") {
r.url += "&" + paramBody
} else {
r.url = r.url + "?" + paramBody
}
} else if r.req.Method == "POST" && r.req.Body == nil {
if len(r.files) > 0 {
pr, pw := io.Pipe()
bodyWriter := multipart.NewWriter(pw)
go func() {
for formname, filename := range r.files {
fileWriter, err := bodyWriter.CreateFormFile(formname, filename)
if err != nil {
log.Fatal(err)
}
fh, err := os.Open(filename)
if err != nil {
log.Fatal(err)
}
// iocopy
_, err = io.Copy(fileWriter, fh)
_ = fh.Close()
if err != nil {
log.Fatal(err)
}
}
for k, v := range r.params {
_ = bodyWriter.WriteField(k, v)
}
_ = bodyWriter.Close()
_ = pw.Close()
}()
r.Header("Content-Type", bodyWriter.FormDataContentType())
r.req.Body = io.NopCloser(pr)
} else if len(paramBody) > 0 {
r.Header("Content-Type", "application/x-www-form-urlencoded")
r.Body(paramBody)
}
}
url, err := url.Parse(r.url)
if err != nil {
return nil, err
}
r.req.URL = url
trans := r.setting.Transport
if trans == nil {
// create default transport
trans = &http.Transport{
TLSClientConfig: r.setting.TLSClientConfig,
Proxy: r.setting.Proxy,
DialContext: TimeoutDialer(r.setting.ConnectTimeout, r.setting.ReadWriteTimeout),
}
} else {
// if r.transport is *http.Transport then set the settings.
if t, ok := trans.(*http.Transport); ok {
if t.TLSClientConfig == nil {
t.TLSClientConfig = r.setting.TLSClientConfig
}
if t.Proxy == nil {
t.Proxy = r.setting.Proxy
}
if t.DialContext == nil {
t.DialContext = TimeoutDialer(r.setting.ConnectTimeout, r.setting.ReadWriteTimeout)
}
}
}
var jar http.CookieJar
if r.setting.EnableCookie {
if defaultCookieJar == nil {
createDefaultCookie()
}
jar = defaultCookieJar
} else {
jar = nil
}
client := &http.Client{
Transport: trans,
Jar: jar,
}
if len(r.setting.UserAgent) > 0 && r.req.Header.Get("User-Agent") == "" {
r.req.Header.Set("User-Agent", r.setting.UserAgent)
}
if r.setting.ShowDebug {
dump, err := httputil.DumpRequest(r.req, true)
if err != nil {
println(err.Error())
}
println(string(dump))
}
resp, err := client.Do(r.req)
if err != nil {
return nil, err
}
r.resp = resp
return resp, nil
}
// String returns the body string in response.
// it calls Response inner.
func (r *Request) String() (string, error) {
data, err := r.Bytes()
if err != nil {
return "", err
}
return string(data), nil
}
// Bytes returns the body []byte in response.
// it calls Response inner.
func (r *Request) Bytes() ([]byte, error) {
if r.body != nil {
return r.body, nil
}
resp, err := r.getResponse()
if err != nil {
return nil, err
}
if resp.Body == nil {
return nil, nil
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
r.body = data
return data, nil
}
// ToFile saves the body data in response to one file.
// it calls Response inner.
func (r *Request) ToFile(filename string) error {
f, err := os.Create(filename)
if err != nil {
return err
}
defer f.Close()
resp, err := r.getResponse()
if err != nil {
return err
}
if resp.Body == nil {
return nil
}
defer resp.Body.Close()
_, err = io.Copy(f, resp.Body)
return err
}
// Response executes request client gets response manually.
func (r *Request) Response() (*http.Response, error) {
return r.getResponse()
}
// TimeoutDialer returns functions of connection dialer with timeout settings for http.Transport Dial field.
func TimeoutDialer(cTimeout, rwTimeout time.Duration) func(ctx context.Context, net, addr string) (c net.Conn, err error) {
return func(ctx context.Context, netw, addr string) (net.Conn, error) {
conn, err := net.DialTimeout(netw, addr, cTimeout)
if err != nil {
return nil, err
}
return conn, conn.SetDeadline(time.Now().Add(rwTimeout))
}
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/conf/static.go | internal/conf/static.go | // Copyright 2020 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package conf
import (
"net/url"
"os"
"time"
"github.com/gogs/go-libravatar"
)
// ℹ️ README: This file contains static values that should only be set at initialization time.
//
// ⚠️ WARNING: After changing any options, do not forget to update template of
// "/admin/config" page as well.
// HasMinWinSvc is whether the application is built with Windows Service support.
//
// ⚠️ WARNING: should only be set by "internal/conf/static_minwinsvc.go".
var HasMinWinSvc bool
// Build time and commit information.
//
// ⚠️ WARNING: should only be set by "-ldflags".
var (
BuildTime string
BuildCommit string
)
// CustomConf returns the absolute path of custom configuration file that is used.
var CustomConf string
var (
// Security settings
Security struct {
InstallLock bool
SecretKey string
LoginRememberDays int
CookieRememberName string
CookieUsername string
CookieSecure bool
EnableLoginStatusCookie bool
LoginStatusCookieName string
LocalNetworkAllowlist []string `delim:","`
}
// Email settings
Email struct {
Enabled bool
SubjectPrefix string
Host string
From string
User string
Password string
DisableHELO bool `ini:"DISABLE_HELO"`
HELOHostname string `ini:"HELO_HOSTNAME"`
SkipVerify bool
UseCertificate bool
CertFile string
KeyFile string
UsePlainText bool
AddPlainTextAlt bool
// Derived from other static values
FromEmail string `ini:"-"` // Parsed email address of From without person's name.
}
// User settings
User struct {
EnableEmailNotification bool
}
// Session settings
Session struct {
Provider string
ProviderConfig string
CookieName string
CookieSecure bool
GCInterval int64 `ini:"GC_INTERVAL"`
MaxLifeTime int64
CSRFCookieName string `ini:"CSRF_COOKIE_NAME"`
}
// Cache settings
Cache struct {
Adapter string
Interval int
Host string
}
// HTTP settings
HTTP struct {
AccessControlAllowOrigin string
}
// Attachment settings
Attachment struct {
Enabled bool
Path string
AllowedTypes []string `delim:"|"`
MaxSize int64
MaxFiles int
}
// Release settings
Release struct {
Attachment struct {
Enabled bool
AllowedTypes []string `delim:"|"`
MaxSize int64
MaxFiles int
} `ini:"release.attachment"`
}
// Time settings
Time struct {
Format string
// Derived from other static values
FormatLayout string `ini:"-"` // Actual layout of the Format.
}
// Mirror settings
Mirror struct {
DefaultInterval int
}
// Webhook settings
Webhook struct {
Types []string
DeliverTimeout int
SkipTLSVerify bool `ini:"SKIP_TLS_VERIFY"`
PagingNum int
}
// Markdown settings
Markdown struct {
EnableHardLineBreak bool
CustomURLSchemes []string `ini:"CUSTOM_URL_SCHEMES"`
FileExtensions []string
}
// Smartypants settings
Smartypants struct {
Enabled bool
Fractions bool
Dashes bool
LatexDashes bool
AngledQuotes bool
}
// Admin settings
Admin struct {
DisableRegularOrgCreation bool
}
// Cron tasks
Cron struct {
UpdateMirror struct {
Enabled bool
RunAtStart bool
Schedule string
} `ini:"cron.update_mirrors"`
RepoHealthCheck struct {
Enabled bool
RunAtStart bool
Schedule string
Timeout time.Duration
Args []string `delim:" "`
} `ini:"cron.repo_health_check"`
CheckRepoStats struct {
Enabled bool
RunAtStart bool
Schedule string
} `ini:"cron.check_repo_stats"`
RepoArchiveCleanup struct {
Enabled bool
RunAtStart bool
Schedule string
OlderThan time.Duration
} `ini:"cron.repo_archive_cleanup"`
}
// Git settings
Git struct {
// ⚠️ WARNING: Should only be set by "internal/db/repo.go".
Version string `ini:"-"`
DisableDiffHighlight bool
MaxDiffFiles int `ini:"MAX_GIT_DIFF_FILES"`
MaxDiffLines int `ini:"MAX_GIT_DIFF_LINES"`
MaxDiffLineChars int `ini:"MAX_GIT_DIFF_LINE_CHARACTERS"`
GCArgs []string `ini:"GC_ARGS" delim:" "`
Timeout struct {
Migrate int
Mirror int
Clone int
Pull int
Diff int
GC int `ini:"GC"`
} `ini:"git.timeout"`
}
// API settings
API struct {
MaxResponseItems int
}
// Prometheus settings
Prometheus struct {
Enabled bool
EnableBasicAuth bool
BasicAuthUsername string
BasicAuthPassword string
}
// Other settings
Other struct {
ShowFooterBranding bool
ShowFooterTemplateLoadTime bool
}
// Global setting
HasRobotsTxt bool
)
type AppOpts struct {
// ⚠️ WARNING: Should only be set by the main package (i.e. "gogs.go").
Version string `ini:"-"`
BrandName string
RunUser string
RunMode string
}
// Application settings
var App AppOpts
type AuthOpts struct {
ActivateCodeLives int
ResetPasswordCodeLives int
RequireEmailConfirmation bool
RequireSigninView bool
DisableRegistration bool
EnableRegistrationCaptcha bool
EnableReverseProxyAuthentication bool
EnableReverseProxyAutoRegistration bool
ReverseProxyAuthenticationHeader string
}
// Authentication settings
var Auth AuthOpts
type ServerOpts struct {
ExternalURL string `ini:"EXTERNAL_URL"`
Domain string
Protocol string
HTTPAddr string `ini:"HTTP_ADDR"`
HTTPPort string `ini:"HTTP_PORT"`
CertFile string
KeyFile string
TLSMinVersion string `ini:"TLS_MIN_VERSION"`
UnixSocketPermission string
LocalRootURL string `ini:"LOCAL_ROOT_URL"`
OfflineMode bool
DisableRouterLog bool
EnableGzip bool
AppDataPath string
LoadAssetsFromDisk bool
LandingURL string `ini:"LANDING_URL"`
// Derived from other static values
URL *url.URL `ini:"-"` // Parsed URL object of ExternalURL.
Subpath string `ini:"-"` // Subpath found the ExternalURL. Should be empty when not found.
SubpathDepth int `ini:"-"` // The number of slashes found in the Subpath.
UnixSocketMode os.FileMode `ini:"-"` // Parsed file mode of UnixSocketPermission.
}
// Server settings
var Server ServerOpts
type SSHOpts struct {
Disabled bool `ini:"DISABLE_SSH"`
Domain string `ini:"SSH_DOMAIN"`
Port int `ini:"SSH_PORT"`
RootPath string `ini:"SSH_ROOT_PATH"`
KeygenPath string `ini:"SSH_KEYGEN_PATH"`
KeyTestPath string `ini:"SSH_KEY_TEST_PATH"`
MinimumKeySizeCheck bool
MinimumKeySizes map[string]int `ini:"-"` // Load from [ssh.minimum_key_sizes]
RewriteAuthorizedKeysAtStart bool
StartBuiltinServer bool `ini:"START_SSH_SERVER"`
ListenHost string `ini:"SSH_LISTEN_HOST"`
ListenPort int `ini:"SSH_LISTEN_PORT"`
ServerCiphers []string `ini:"SSH_SERVER_CIPHERS"`
ServerMACs []string `ini:"SSH_SERVER_MACS"`
ServerAlgorithms []string `ini:"SSH_SERVER_ALGORITHMS"`
}
// SSH settings
var SSH SSHOpts
type RepositoryOpts struct {
Root string
ScriptType string
ANSICharset string `ini:"ANSI_CHARSET"`
ForcePrivate bool
MaxCreationLimit int
PreferredLicenses []string
DisableHTTPGit bool `ini:"DISABLE_HTTP_GIT"`
EnableLocalPathMigration bool
EnableRawFileRenderMode bool
CommitsFetchConcurrency int
DefaultBranch string
// Repository editor settings
Editor struct {
LineWrapExtensions []string
PreviewableFileModes []string
} `ini:"repository.editor"`
// Repository upload settings
Upload struct {
Enabled bool
TempPath string
AllowedTypes []string `delim:"|"`
FileMaxSize int64
MaxFiles int
} `ini:"repository.upload"`
}
// Repository settings
var Repository RepositoryOpts
type DatabaseOpts struct {
Type string
Host string
Name string
Schema string
User string
Password string
SSLMode string `ini:"SSL_MODE"`
Path string
MaxOpenConns int
MaxIdleConns int
}
// Database settings
var Database DatabaseOpts
type LFSOpts struct {
Storage string
ObjectsPath string
}
// LFS settings
var LFS LFSOpts
type UIUserOpts struct {
RepoPagingNum int
NewsFeedPagingNum int
CommitsPagingNum int
}
type UIOpts struct {
ExplorePagingNum int
IssuePagingNum int
FeedMaxCommitNum int
ThemeColorMetaTag string
MaxDisplayFileSize int64
Admin struct {
UserPagingNum int
RepoPagingNum int
NoticePagingNum int
OrgPagingNum int
} `ini:"ui.admin"`
User UIUserOpts `ini:"ui.user"`
}
// UI settings
var UI UIOpts
type PictureOpts struct {
AvatarUploadPath string
RepositoryAvatarUploadPath string
GravatarSource string
DisableGravatar bool
EnableFederatedAvatar bool
// Derived from other static values
LibravatarService *libravatar.Libravatar `ini:"-"` // Initialized client for federated avatar.
}
// Picture settings
var Picture PictureOpts
type i18nConf struct {
Langs []string `delim:","`
Names []string `delim:","`
dateLangs map[string]string `ini:"-"`
}
// DateLang transforms standard language locale name to corresponding value in datetime plugin.
func (c *i18nConf) DateLang(lang string) string {
name, ok := c.dateLangs[lang]
if ok {
return name
}
return "en"
}
// I18n settings
var I18n *i18nConf
// handleDeprecated transfers deprecated values to the new ones when set.
func handleDeprecated() {
// Add fallback logic here, example:
// if App.AppName != "" {
// App.BrandName = App.AppName
// App.AppName = ""
// }
}
// HookMode indicates whether program starts as Git server-side hook callback.
// All operations should be done synchronously to prevent program exits before finishing.
//
// ⚠️ WARNING: Should only be set by "internal/cmd/serv.go".
var HookMode bool
// Indicates which database backend is currently being used.
var (
UseSQLite3 bool
UseMySQL bool
UsePostgreSQL bool
UseMSSQL bool
)
// UsersAvatarPathPrefix is the path prefix to user avatars.
const UsersAvatarPathPrefix = "avatars"
// UserDefaultAvatarURLPath returns the URL path of the default user avatar.
func UserDefaultAvatarURLPath() string {
return Server.Subpath + "/img/avatar_default.png"
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/conf/mocks.go | internal/conf/mocks.go | // Copyright 2020 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package conf
import (
"sync"
"testing"
)
func SetMockApp(t *testing.T, opts AppOpts) {
before := App
App = opts
t.Cleanup(func() {
App = before
})
}
func SetMockAuth(t *testing.T, otps AuthOpts) {
before := Auth
Auth = otps
t.Cleanup(func() {
Auth = before
})
}
var mockServer sync.Mutex
func SetMockServer(t *testing.T, opts ServerOpts) {
mockServer.Lock()
before := Server
Server = opts
t.Cleanup(func() {
Server = before
mockServer.Unlock()
})
}
var mockSSH sync.Mutex
func SetMockSSH(t *testing.T, opts SSHOpts) {
mockSSH.Lock()
before := SSH
SSH = opts
t.Cleanup(func() {
SSH = before
mockSSH.Unlock()
})
}
var mockRepository sync.Mutex
func SetMockRepository(t *testing.T, opts RepositoryOpts) {
mockRepository.Lock()
before := Repository
Repository = opts
t.Cleanup(func() {
Repository = before
mockRepository.Unlock()
})
}
func SetMockUI(t *testing.T, opts UIOpts) {
before := UI
UI = opts
t.Cleanup(func() {
UI = before
})
}
var mockPicture sync.Mutex
func SetMockPicture(t *testing.T, opts PictureOpts) {
mockPicture.Lock()
before := Picture
Picture = opts
t.Cleanup(func() {
Picture = before
mockPicture.Unlock()
})
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/conf/computed_test.go | internal/conf/computed_test.go | // Copyright 2020 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package conf
import (
"fmt"
"os"
"testing"
"github.com/stretchr/testify/assert"
"gogs.io/gogs/internal/testutil"
)
func TestIsProdMode(t *testing.T) {
before := App.RunMode
defer func() {
App.RunMode = before
}()
tests := []struct {
mode string
want bool
}{
{mode: "dev", want: false},
{mode: "test", want: false},
{mode: "prod", want: true},
{mode: "Prod", want: true},
{mode: "PROD", want: true},
}
for _, test := range tests {
t.Run("", func(t *testing.T) {
App.RunMode = test.mode
assert.Equal(t, test.want, IsProdMode())
})
}
}
func TestWorkDirHelper(_ *testing.T) {
if !testutil.WantHelperProcess() {
return
}
fmt.Fprintln(os.Stdout, WorkDir())
}
func TestWorkDir(t *testing.T) {
tests := []struct {
env string
want string
}{
{env: "GOGS_WORK_DIR=/tmp", want: "/tmp"},
{env: "", want: WorkDir()},
}
for _, test := range tests {
t.Run("", func(t *testing.T) {
out, err := testutil.Exec("TestWorkDirHelper", test.env)
if err != nil {
t.Fatal(err)
}
assert.Equal(t, test.want, out)
})
}
}
func TestCustomDirHelper(_ *testing.T) {
if !testutil.WantHelperProcess() {
return
}
fmt.Fprintln(os.Stdout, CustomDir())
}
func TestCustomDir(t *testing.T) {
tests := []struct {
env string
want string
}{
{env: "GOGS_CUSTOM=/tmp", want: "/tmp"},
{env: "", want: CustomDir()},
}
for _, test := range tests {
t.Run("", func(t *testing.T) {
out, err := testutil.Exec("TestCustomDirHelper", test.env)
if err != nil {
t.Fatal(err)
}
assert.Equal(t, test.want, out)
})
}
}
func TestHomeDirHelper(_ *testing.T) {
if !testutil.WantHelperProcess() {
return
}
fmt.Fprintln(os.Stdout, HomeDir())
}
func TestHomeDir(t *testing.T) {
tests := []struct {
envs []string
want string
}{
{envs: []string{"HOME=/tmp"}, want: "/tmp"},
{envs: []string{`USERPROFILE=C:\Users\Joe`}, want: `C:\Users\Joe`},
{envs: []string{`HOMEDRIVE=C:`, `HOMEPATH=\Users\Joe`}, want: `C:\Users\Joe`},
{envs: nil, want: ""},
}
for _, test := range tests {
t.Run("", func(t *testing.T) {
out, err := testutil.Exec("TestHomeDirHelper", test.envs...)
if err != nil {
t.Fatal(err)
}
assert.Equal(t, test.want, out)
})
}
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/conf/log_test.go | internal/conf/log_test.go | // Copyright 2020 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package conf
import (
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"gopkg.in/ini.v1"
log "unknwon.dev/clog/v2"
)
func Test_initLogConf(t *testing.T) {
t.Run("missing configuration section", func(t *testing.T) {
f, err := ini.Load([]byte(`
[log]
MODE = console
`))
if err != nil {
t.Fatal(err)
}
got, hasConsole, err := initLogConf(f, false)
assert.NotNil(t, err)
assert.Equal(t, `missing configuration section [log.console] for "console" logger`, err.Error())
assert.False(t, hasConsole)
assert.Nil(t, got)
})
t.Run("no console logger", func(t *testing.T) {
f, err := ini.Load([]byte(`
[log]
MODE = file
[log.file]
`))
if err != nil {
t.Fatal(err)
}
got, hasConsole, err := initLogConf(f, false)
if err != nil {
t.Fatal(err)
}
assert.False(t, hasConsole)
assert.NotNil(t, got)
})
f, err := ini.Load([]byte(`
[log]
ROOT_PATH = log
MODE = console, file, slack, discord
BUFFER_LEN = 50
LEVEL = trace
[log.console]
BUFFER_LEN = 10
[log.file]
LEVEL = INFO
LOG_ROTATE = true
DAILY_ROTATE = true
MAX_SIZE_SHIFT = 20
MAX_LINES = 1000
MAX_DAYS = 3
[log.slack]
LEVEL = Warn
URL = https://slack.com
[log.discord]
LEVEL = error
URL = https://discordapp.com
USERNAME = yoyo
`))
if err != nil {
t.Fatal(err)
}
got, hasConsole, err := initLogConf(f, false)
if err != nil {
t.Fatal(err)
}
logConf := &logConf{
RootPath: filepath.Join(WorkDir(), "log"),
Modes: []string{
log.DefaultConsoleName,
log.DefaultFileName,
log.DefaultSlackName,
log.DefaultDiscordName,
},
Configs: []*loggerConf{
{
Buffer: 10,
Config: log.ConsoleConfig{
Level: log.LevelTrace,
},
}, {
Buffer: 50,
Config: log.FileConfig{
Level: log.LevelInfo,
Filename: filepath.Join(WorkDir(), "log", "gogs.log"),
FileRotationConfig: log.FileRotationConfig{
Rotate: true,
Daily: true,
MaxSize: 1 << 20,
MaxLines: 1000,
MaxDays: 3,
},
},
}, {
Buffer: 50,
Config: log.SlackConfig{
Level: log.LevelWarn,
URL: "https://slack.com",
},
}, {
Buffer: 50,
Config: log.DiscordConfig{
Level: log.LevelError,
URL: "https://discordapp.com",
Username: "yoyo",
},
},
},
}
assert.True(t, hasConsole)
assert.Equal(t, logConf, got)
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/conf/utils.go | internal/conf/utils.go | // Copyright 2020 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package conf
import (
"path/filepath"
"strings"
"github.com/pkg/errors"
"gogs.io/gogs/internal/osutil"
"gogs.io/gogs/internal/process"
)
// cleanUpOpenSSHVersion cleans up the raw output of "ssh -V" and returns a clean version string.
func cleanUpOpenSSHVersion(raw string) string {
v := strings.TrimRight(strings.Fields(raw)[0], ",1234567890")
v = strings.TrimSuffix(strings.TrimPrefix(v, "OpenSSH_"), "p")
return v
}
// openSSHVersion returns string representation of OpenSSH version via command "ssh -V".
func openSSHVersion() (string, error) {
// NOTE: Somehow the version is printed to stderr.
_, stderr, err := process.Exec("conf.openSSHVersion", "ssh", "-V")
if err != nil {
return "", errors.Wrap(err, stderr)
}
return cleanUpOpenSSHVersion(stderr), nil
}
// ensureAbs prepends the WorkDir to the given path if it is not an absolute path.
func ensureAbs(path string) string {
if filepath.IsAbs(path) {
return path
}
return filepath.Join(WorkDir(), path)
}
// CheckRunUser returns false if configured run user does not match actual user that
// runs the app. The first return value is the actual user name. This check is ignored
// under Windows since SSH remote login is not the main method to login on Windows.
func CheckRunUser(runUser string) (string, bool) {
if IsWindowsRuntime() {
return "", true
}
currentUser := osutil.CurrentUsername()
return currentUser, runUser == currentUser
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/conf/conf.go | internal/conf/conf.go | // Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package conf
import (
"fmt"
"net/mail"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"time"
_ "github.com/go-macaron/cache/memcache"
_ "github.com/go-macaron/cache/redis"
_ "github.com/go-macaron/session/redis"
"github.com/gogs/go-libravatar"
"github.com/pkg/errors"
"gopkg.in/ini.v1"
log "unknwon.dev/clog/v2"
"gogs.io/gogs/conf"
"gogs.io/gogs/internal/osutil"
"gogs.io/gogs/internal/semverutil"
)
func init() {
// Initialize the primary logger until logging service is up.
err := log.NewConsole()
if err != nil {
panic("init console logger: " + err.Error())
}
}
// File is the configuration object.
var File *ini.File
// Init initializes configuration from conf assets and given custom configuration file.
// If `customConf` is empty, it falls back to default location, i.e. "<WORK DIR>/custom".
// It is safe to call this function multiple times with desired `customConf`, but it is
// not concurrent safe.
//
// NOTE: The order of loading configuration sections matters as one may depend on another.
//
// ⚠️ WARNING: Do not print anything in this function other than warnings.
func Init(customConf string) error {
data, err := conf.Files.ReadFile("app.ini")
if err != nil {
return errors.Wrap(err, `read default "app.ini"`)
}
File, err = ini.LoadSources(ini.LoadOptions{
IgnoreInlineComment: true,
}, data)
if err != nil {
return errors.Wrap(err, `parse "app.ini"`)
}
File.NameMapper = ini.SnackCase
File.ValueMapper = os.ExpandEnv
if customConf == "" {
customConf = filepath.Join(CustomDir(), "conf", "app.ini")
} else {
customConf, err = filepath.Abs(customConf)
if err != nil {
return errors.Wrap(err, "get absolute path")
}
}
CustomConf = customConf
if osutil.IsFile(customConf) {
if err = File.Append(customConf); err != nil {
return errors.Wrapf(err, "append %q", customConf)
}
} else {
log.Warn("Custom config %q not found. Ignore this warning if you're running for the first time", customConf)
}
if err = File.Section(ini.DefaultSection).MapTo(&App); err != nil {
return errors.Wrap(err, "mapping default section")
}
// ***************************
// ----- Server settings -----
// ***************************
if err = File.Section("server").MapTo(&Server); err != nil {
return errors.Wrap(err, "mapping [server] section")
}
Server.AppDataPath = ensureAbs(Server.AppDataPath)
if !strings.HasSuffix(Server.ExternalURL, "/") {
Server.ExternalURL += "/"
}
Server.URL, err = url.Parse(Server.ExternalURL)
if err != nil {
return errors.Wrapf(err, "parse '[server] EXTERNAL_URL' %q", err)
}
// Subpath should start with '/' and end without '/', i.e. '/{subpath}'.
Server.Subpath = strings.TrimRight(Server.URL.Path, "/")
Server.SubpathDepth = strings.Count(Server.Subpath, "/")
unixSocketMode, err := strconv.ParseUint(Server.UnixSocketPermission, 8, 32)
if err != nil {
return errors.Wrapf(err, "parse '[server] UNIX_SOCKET_PERMISSION' %q", Server.UnixSocketPermission)
}
if unixSocketMode > 0777 {
unixSocketMode = 0666
}
Server.UnixSocketMode = os.FileMode(unixSocketMode)
// ************************
// ----- SSH settings -----
// ************************
SSH.RootPath = filepath.Join(HomeDir(), ".ssh")
SSH.KeyTestPath = os.TempDir()
if err = File.Section("server").MapTo(&SSH); err != nil {
return errors.Wrap(err, "mapping SSH settings from [server] section")
}
SSH.RootPath = ensureAbs(SSH.RootPath)
SSH.KeyTestPath = ensureAbs(SSH.KeyTestPath)
if !SSH.Disabled {
if !SSH.StartBuiltinServer {
if err := os.MkdirAll(SSH.RootPath, 0700); err != nil {
return errors.Wrap(err, "create SSH root directory")
} else if err = os.MkdirAll(SSH.KeyTestPath, 0644); err != nil {
return errors.Wrap(err, "create SSH key test directory")
}
} else {
SSH.RewriteAuthorizedKeysAtStart = false
}
// Check if server is eligible for minimum key size check when user choose to enable.
// Windows server and OpenSSH version lower than 5.1 are forced to be disabled because
// the "ssh-keygen" in Windows does not print key type.
// See https://github.com/gogs/gogs/issues/4507.
if SSH.MinimumKeySizeCheck {
sshVersion, err := openSSHVersion()
if err != nil {
return errors.Wrap(err, "get OpenSSH version")
}
if IsWindowsRuntime() || semverutil.Compare(sshVersion, "<", "5.1") {
log.Warn(`SSH minimum key size check is forced to be disabled because server is not eligible:
1. Windows server
2. OpenSSH version is lower than 5.1`)
} else {
SSH.MinimumKeySizes = map[string]int{}
for _, key := range File.Section("ssh.minimum_key_sizes").Keys() {
if key.MustInt() != -1 {
SSH.MinimumKeySizes[strings.ToLower(key.Name())] = key.MustInt()
}
}
}
}
}
// *******************************
// ----- Repository settings -----
// *******************************
Repository.Root = filepath.Join(HomeDir(), "gogs-repositories")
if err = File.Section("repository").MapTo(&Repository); err != nil {
return errors.Wrap(err, "mapping [repository] section")
}
Repository.Root = ensureAbs(Repository.Root)
Repository.Upload.TempPath = ensureAbs(Repository.Upload.TempPath)
// *****************************
// ----- Database settings -----
// *****************************
if err = File.Section("database").MapTo(&Database); err != nil {
return errors.Wrap(err, "mapping [database] section")
}
Database.Path = ensureAbs(Database.Path)
// *****************************
// ----- Security settings -----
// *****************************
if err = File.Section("security").MapTo(&Security); err != nil {
return errors.Wrap(err, "mapping [security] section")
}
// Check run user when the install is locked.
if Security.InstallLock {
currentUser, match := CheckRunUser(App.RunUser)
if !match {
return fmt.Errorf("user configured to run Gogs is %q, but the current user is %q", App.RunUser, currentUser)
}
}
// **************************
// ----- Email settings -----
// **************************
if err = File.Section("email").MapTo(&Email); err != nil {
return errors.Wrap(err, "mapping [email] section")
}
if Email.Enabled {
if Email.From == "" {
Email.From = Email.User
}
parsed, err := mail.ParseAddress(Email.From)
if err != nil {
return errors.Wrapf(err, "parse mail address %q", Email.From)
}
Email.FromEmail = parsed.Address
}
// ***********************************
// ----- Authentication settings -----
// ***********************************
if err = File.Section("auth").MapTo(&Auth); err != nil {
return errors.Wrap(err, "mapping [auth] section")
}
// *************************
// ----- User settings -----
// *************************
if err = File.Section("user").MapTo(&User); err != nil {
return errors.Wrap(err, "mapping [user] section")
}
// ****************************
// ----- Session settings -----
// ****************************
if err = File.Section("session").MapTo(&Session); err != nil {
return errors.Wrap(err, "mapping [session] section")
}
// *******************************
// ----- Attachment settings -----
// *******************************
if err = File.Section("attachment").MapTo(&Attachment); err != nil {
return errors.Wrap(err, "mapping [attachment] section")
}
Attachment.Path = ensureAbs(Attachment.Path)
// *************************
// ----- Time settings -----
// *************************
if err = File.Section("time").MapTo(&Time); err != nil {
return errors.Wrap(err, "mapping [time] section")
}
Time.FormatLayout = map[string]string{
"ANSIC": time.ANSIC,
"UnixDate": time.UnixDate,
"RubyDate": time.RubyDate,
"RFC822": time.RFC822,
"RFC822Z": time.RFC822Z,
"RFC850": time.RFC850,
"RFC1123": time.RFC1123,
"RFC1123Z": time.RFC1123Z,
"RFC3339": time.RFC3339,
"RFC3339Nano": time.RFC3339Nano,
"Kitchen": time.Kitchen,
"Stamp": time.Stamp,
"StampMilli": time.StampMilli,
"StampMicro": time.StampMicro,
"StampNano": time.StampNano,
}[Time.Format]
if Time.FormatLayout == "" {
Time.FormatLayout = time.RFC3339
}
// ****************************
// ----- Picture settings -----
// ****************************
if err = File.Section("picture").MapTo(&Picture); err != nil {
return errors.Wrap(err, "mapping [picture] section")
}
Picture.AvatarUploadPath = ensureAbs(Picture.AvatarUploadPath)
Picture.RepositoryAvatarUploadPath = ensureAbs(Picture.RepositoryAvatarUploadPath)
switch Picture.GravatarSource {
case "gravatar":
Picture.GravatarSource = "https://secure.gravatar.com/avatar/"
case "libravatar":
Picture.GravatarSource = "https://seccdn.libravatar.org/avatar/"
}
if Server.OfflineMode {
Picture.DisableGravatar = true
Picture.EnableFederatedAvatar = false
}
if Picture.DisableGravatar {
Picture.EnableFederatedAvatar = false
}
if Picture.EnableFederatedAvatar {
gravatarURL, err := url.Parse(Picture.GravatarSource)
if err != nil {
return errors.Wrapf(err, "parse Gravatar source %q", Picture.GravatarSource)
}
Picture.LibravatarService = libravatar.New()
if gravatarURL.Scheme == "https" {
Picture.LibravatarService.SetUseHTTPS(true)
Picture.LibravatarService.SetSecureFallbackHost(gravatarURL.Host)
} else {
Picture.LibravatarService.SetUseHTTPS(false)
Picture.LibravatarService.SetFallbackHost(gravatarURL.Host)
}
}
// ***************************
// ----- Mirror settings -----
// ***************************
if err = File.Section("mirror").MapTo(&Mirror); err != nil {
return errors.Wrap(err, "mapping [mirror] section")
}
if Mirror.DefaultInterval <= 0 {
Mirror.DefaultInterval = 8
}
// *************************
// ----- I18n settings -----
// *************************
I18n = new(i18nConf)
if err = File.Section("i18n").MapTo(I18n); err != nil {
return errors.Wrap(err, "mapping [i18n] section")
}
I18n.dateLangs = File.Section("i18n.datelang").KeysHash()
// *************************
// ----- LFS settings -----
// *************************
if err = File.Section("lfs").MapTo(&LFS); err != nil {
return errors.Wrap(err, "mapping [lfs] section")
}
LFS.ObjectsPath = ensureAbs(LFS.ObjectsPath)
handleDeprecated()
if err = File.Section("cache").MapTo(&Cache); err != nil {
return errors.Wrap(err, "mapping [cache] section")
} else if err = File.Section("http").MapTo(&HTTP); err != nil {
return errors.Wrap(err, "mapping [http] section")
} else if err = File.Section("release").MapTo(&Release); err != nil {
return errors.Wrap(err, "mapping [release] section")
} else if err = File.Section("webhook").MapTo(&Webhook); err != nil {
return errors.Wrap(err, "mapping [webhook] section")
} else if err = File.Section("markdown").MapTo(&Markdown); err != nil {
return errors.Wrap(err, "mapping [markdown] section")
} else if err = File.Section("smartypants").MapTo(&Smartypants); err != nil {
return errors.Wrap(err, "mapping [smartypants] section")
} else if err = File.Section("admin").MapTo(&Admin); err != nil {
return errors.Wrap(err, "mapping [admin] section")
} else if err = File.Section("cron").MapTo(&Cron); err != nil {
return errors.Wrap(err, "mapping [cron] section")
} else if err = File.Section("git").MapTo(&Git); err != nil {
return errors.Wrap(err, "mapping [git] section")
} else if err = File.Section("api").MapTo(&API); err != nil {
return errors.Wrap(err, "mapping [api] section")
} else if err = File.Section("ui").MapTo(&UI); err != nil {
return errors.Wrap(err, "mapping [ui] section")
} else if err = File.Section("prometheus").MapTo(&Prometheus); err != nil {
return errors.Wrap(err, "mapping [prometheus] section")
} else if err = File.Section("other").MapTo(&Other); err != nil {
return errors.Wrap(err, "mapping [other] section")
}
HasRobotsTxt = osutil.IsFile(filepath.Join(CustomDir(), "robots.txt"))
return nil
}
// MustInit panics if configuration initialization failed.
func MustInit(customConf string) {
err := Init(customConf)
if err != nil {
panic(err)
}
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/conf/static_minwinsvc.go | internal/conf/static_minwinsvc.go | //go:build minwinsvc
// Copyright 2015 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package conf
import (
_ "github.com/gogs/minwinsvc"
)
func init() {
HasMinWinSvc = true
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/conf/log.go | internal/conf/log.go | // Copyright 2020 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package conf
import (
"os"
"path/filepath"
"strings"
"github.com/pkg/errors"
"gopkg.in/ini.v1"
log "unknwon.dev/clog/v2"
)
type loggerConf struct {
Buffer int64
Config any
}
type logConf struct {
RootPath string
Modes []string
Configs []*loggerConf
}
// Log settings
var Log *logConf
// initLogConf returns parsed logging configuration from given INI file. When the
// argument "hookMode" is true, it only initializes the root path for log files.
// NOTE: Because we always create a console logger as the primary logger at init time,
// we need to remove it in case the user doesn't configure to use it after the logging
// service is initialized.
func initLogConf(cfg *ini.File, hookMode bool) (_ *logConf, hasConsole bool, _ error) {
rootPath := cfg.Section("log").Key("ROOT_PATH").MustString(filepath.Join(WorkDir(), "log"))
if hookMode {
return &logConf{
RootPath: ensureAbs(rootPath),
}, false, nil
}
modes := strings.Split(cfg.Section("log").Key("MODE").MustString("console"), ",")
lc := &logConf{
RootPath: ensureAbs(rootPath),
Modes: make([]string, 0, len(modes)),
Configs: make([]*loggerConf, 0, len(modes)),
}
// Iterate over [log.*] sections to initialize individual logger.
levelMappings := map[string]log.Level{
"trace": log.LevelTrace,
"info": log.LevelInfo,
"warn": log.LevelWarn,
"error": log.LevelError,
"fatal": log.LevelFatal,
}
for i := range modes {
modes[i] = strings.ToLower(strings.TrimSpace(modes[i]))
secName := "log." + modes[i]
sec, err := cfg.GetSection(secName)
if err != nil {
return nil, hasConsole, errors.Errorf("missing configuration section [%s] for %q logger", secName, modes[i])
}
level := levelMappings[strings.ToLower(sec.Key("LEVEL").MustString("trace"))]
buffer := sec.Key("BUFFER_LEN").MustInt64(100)
var c *loggerConf
switch modes[i] {
case log.DefaultConsoleName:
hasConsole = true
c = &loggerConf{
Buffer: buffer,
Config: log.ConsoleConfig{
Level: level,
},
}
case log.DefaultFileName:
logPath := filepath.Join(lc.RootPath, "gogs.log")
c = &loggerConf{
Buffer: buffer,
Config: log.FileConfig{
Level: level,
Filename: logPath,
FileRotationConfig: log.FileRotationConfig{
Rotate: sec.Key("LOG_ROTATE").MustBool(true),
Daily: sec.Key("DAILY_ROTATE").MustBool(true),
MaxSize: 1 << uint(sec.Key("MAX_SIZE_SHIFT").MustInt(28)),
MaxLines: sec.Key("MAX_LINES").MustInt64(1000000),
MaxDays: sec.Key("MAX_DAYS").MustInt64(7),
},
},
}
case log.DefaultSlackName:
c = &loggerConf{
Buffer: buffer,
Config: log.SlackConfig{
Level: level,
URL: sec.Key("URL").String(),
},
}
case log.DefaultDiscordName:
c = &loggerConf{
Buffer: buffer,
Config: log.DiscordConfig{
Level: level,
URL: sec.Key("URL").String(),
Username: sec.Key("USERNAME").String(),
},
}
default:
continue
}
lc.Modes = append(lc.Modes, modes[i])
lc.Configs = append(lc.Configs, c)
}
return lc, hasConsole, nil
}
// InitLogging initializes the logging service of the application. When the
// "hookMode" is true, it only initializes the root path for log files without
// creating any logger. It will also not remove the primary logger in "hookMode"
// and is up to the caller to decide when to remove it.
func InitLogging(hookMode bool) {
logConf, hasConsole, err := initLogConf(File, hookMode)
if err != nil {
log.Fatal("Failed to init logging configuration: %v", err)
}
defer func() {
Log = logConf
}()
if hookMode {
return
}
err = os.MkdirAll(logConf.RootPath, os.ModePerm)
if err != nil {
log.Fatal("Failed to create log directory: %v", err)
}
for i, mode := range logConf.Modes {
c := logConf.Configs[i]
var err error
var level log.Level
switch mode {
case log.DefaultConsoleName:
level = c.Config.(log.ConsoleConfig).Level
err = log.NewConsole(c.Buffer, c.Config)
case log.DefaultFileName:
level = c.Config.(log.FileConfig).Level
err = log.NewFile(c.Buffer, c.Config)
case log.DefaultSlackName:
level = c.Config.(log.SlackConfig).Level
err = log.NewSlack(c.Buffer, c.Config)
case log.DefaultDiscordName:
level = c.Config.(log.DiscordConfig).Level
err = log.NewDiscord(c.Buffer, c.Config)
default:
panic("unreachable")
}
if err != nil {
log.Fatal("Failed to init %s logger: %v", mode, err)
return
}
log.Trace("Log mode: %s (%s)", strings.Title(mode), strings.Title(strings.ToLower(level.String())))
}
// ⚠️ WARNING: It is only safe to remove the primary logger until
// there are other loggers that are initialized. Otherwise, the
// application will print errors to nowhere.
if !hasConsole {
log.Remove(log.DefaultConsoleName)
}
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/conf/utils_test.go | internal/conf/utils_test.go | // Copyright 2020 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package conf
import (
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
)
func Test_cleanUpOpenSSHVersion(t *testing.T) {
tests := []struct {
raw string
want string
}{
{
raw: "OpenSSH_7.4p1 Ubuntu-10, OpenSSL 1.0.2g 1 Mar 2016",
want: "7.4",
}, {
raw: "OpenSSH_5.3p1, OpenSSL 1.0.1e-fips 11 Feb 2013",
want: "5.3",
}, {
raw: "OpenSSH_4.3p2, OpenSSL 0.9.8e-fips-rhel5 01 Jul 2008",
want: "4.3",
},
}
for _, test := range tests {
t.Run("", func(t *testing.T) {
assert.Equal(t, test.want, cleanUpOpenSSHVersion(test.raw))
})
}
}
func Test_ensureAbs(t *testing.T) {
wd := WorkDir()
tests := []struct {
path string
want string
}{
{
path: "data/avatars",
want: filepath.Join(wd, "data", "avatars"),
}, {
path: wd,
want: wd,
},
}
for _, test := range tests {
t.Run("", func(t *testing.T) {
assert.Equal(t, test.want, ensureAbs(test.path))
})
}
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/conf/static_test.go | internal/conf/static_test.go | // Copyright 2020 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package conf
import (
"testing"
"github.com/stretchr/testify/assert"
)
func Test_i18n_DateLang(t *testing.T) {
c := &i18nConf{
dateLangs: map[string]string{
"en-US": "en",
"zh-CN": "zh",
},
}
tests := []struct {
lang string
want string
}{
{lang: "en-US", want: "en"},
{lang: "zh-CN", want: "zh"},
{lang: "jp-JP", want: "en"},
}
for _, test := range tests {
t.Run("", func(t *testing.T) {
assert.Equal(t, test.want, c.DateLang(test.lang))
})
}
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/conf/conf_test.go | internal/conf/conf_test.go | // Copyright 2020 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package conf
import (
"bytes"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"gopkg.in/ini.v1"
"gogs.io/gogs/internal/testutil"
)
func TestInit(t *testing.T) {
ini.PrettyFormat = false
defer func() {
MustInit("")
ini.PrettyFormat = true
}()
assert.Nil(t, Init(filepath.Join("testdata", "custom.ini")))
cfg := ini.Empty()
cfg.NameMapper = ini.SnackCase
for _, v := range []struct {
section string
config any
}{
{"", &App},
{"server", &Server},
{"server", &SSH},
{"repository", &Repository},
{"database", &Database},
{"security", &Security},
{"email", &Email},
{"auth", &Auth},
{"user", &User},
{"session", &Session},
{"attachment", &Attachment},
{"time", &Time},
{"picture", &Picture},
{"mirror", &Mirror},
{"i18n", &I18n},
} {
err := cfg.Section(v.section).ReflectFrom(v.config)
if err != nil {
t.Fatalf("%s: %v", v.section, err)
}
}
buf := new(bytes.Buffer)
_, err := cfg.WriteTo(buf)
if err != nil {
t.Fatal(err)
}
testutil.AssertGolden(t, filepath.Join("testdata", "TestInit.golden.ini"), testutil.Update("TestInit"), buf.String())
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/conf/computed.go | internal/conf/computed.go | // Copyright 2020 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package conf
import (
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync"
)
// ℹ️ README: This file contains configuration values that require computation to be useful.
// IsWindowsRuntime returns true if the current runtime in Windows.
func IsWindowsRuntime() bool {
return runtime.GOOS == "windows"
}
// IsProdMode returns true if the application is running in production mode.
func IsProdMode() bool {
return strings.EqualFold(App.RunMode, "prod")
}
var (
appPath string
appPathOnce sync.Once
)
// AppPath returns the absolute path of the application's binary.
func AppPath() string {
appPathOnce.Do(func() {
var err error
appPath, err = exec.LookPath(os.Args[0])
if err != nil {
panic("look executable path: " + err.Error())
}
appPath, err = filepath.Abs(appPath)
if err != nil {
panic("get absolute executable path: " + err.Error())
}
})
return appPath
}
var (
workDir string
workDirOnce sync.Once
)
// WorkDir returns the absolute path of work directory. It reads the value of environment
// variable GOGS_WORK_DIR. When not set, it uses the directory where the application's
// binary is located.
func WorkDir() string {
workDirOnce.Do(func() {
workDir = os.Getenv("GOGS_WORK_DIR")
if workDir != "" {
return
}
workDir = filepath.Dir(AppPath())
})
return workDir
}
var (
customDir string
customDirOnce sync.Once
)
// CustomDir returns the absolute path of the custom directory that contains local overrides.
// It reads the value of environment variable GOGS_CUSTOM. When not set, it uses the work
// directory returned by WorkDir function.
func CustomDir() string {
customDirOnce.Do(func() {
customDir = os.Getenv("GOGS_CUSTOM")
if customDir != "" {
return
}
customDir = filepath.Join(WorkDir(), "custom")
})
return customDir
}
var (
homeDir string
homeDirOnce sync.Once
)
// HomeDir returns the home directory by reading environment variables. It may return empty
// string when environment variables are not set.
func HomeDir() string {
homeDirOnce.Do(func() {
homeDir = os.Getenv("HOME")
if homeDir != "" {
return
}
homeDir = os.Getenv("USERPROFILE")
if homeDir != "" {
return
}
homeDir = os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
})
return homeDir
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/lazyregexp/lazyre.go | internal/lazyregexp/lazyre.go | // Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package lazyregexp is a thin wrapper over regexp, allowing the use of global
// regexp variables without forcing them to be compiled at init.
package lazyregexp
import (
"regexp"
"sync"
"gogs.io/gogs/internal/testutil"
)
// Regexp is a wrapper around regexp.Regexp, where the underlying regexp will be
// compiled the first time it is needed.
type Regexp struct {
str string
once sync.Once
rx *regexp.Regexp
}
func (r *Regexp) Regexp() *regexp.Regexp {
r.once.Do(r.build)
return r.rx
}
func (r *Regexp) build() {
r.rx = regexp.MustCompile(r.str)
r.str = ""
}
func (r *Regexp) Find(b []byte) []byte {
return r.Regexp().Find(b)
}
func (r *Regexp) FindSubmatch(s []byte) [][]byte {
return r.Regexp().FindSubmatch(s)
}
func (r *Regexp) FindStringSubmatch(s string) []string {
return r.Regexp().FindStringSubmatch(s)
}
func (r *Regexp) FindStringSubmatchIndex(s string) []int {
return r.Regexp().FindStringSubmatchIndex(s)
}
func (r *Regexp) ReplaceAllString(src, repl string) string {
return r.Regexp().ReplaceAllString(src, repl)
}
func (r *Regexp) FindString(s string) string {
return r.Regexp().FindString(s)
}
func (r *Regexp) FindAll(b []byte, n int) [][]byte {
return r.Regexp().FindAll(b, n)
}
func (r *Regexp) FindAllString(s string, n int) []string {
return r.Regexp().FindAllString(s, n)
}
func (r *Regexp) MatchString(s string) bool {
return r.Regexp().MatchString(s)
}
func (r *Regexp) SubexpNames() []string {
return r.Regexp().SubexpNames()
}
func (r *Regexp) FindAllStringSubmatch(s string, n int) [][]string {
return r.Regexp().FindAllStringSubmatch(s, n)
}
func (r *Regexp) Split(s string, n int) []string {
return r.Regexp().Split(s, n)
}
func (r *Regexp) ReplaceAllLiteralString(src, repl string) string {
return r.Regexp().ReplaceAllLiteralString(src, repl)
}
func (r *Regexp) FindAllIndex(b []byte, n int) [][]int {
return r.Regexp().FindAllIndex(b, n)
}
func (r *Regexp) Match(b []byte) bool {
return r.Regexp().Match(b)
}
func (r *Regexp) ReplaceAllStringFunc(src string, repl func(string) string) string {
return r.Regexp().ReplaceAllStringFunc(src, repl)
}
func (r *Regexp) ReplaceAll(src, repl []byte) []byte {
return r.Regexp().ReplaceAll(src, repl)
}
// New creates a new lazy regexp, delaying the compiling work until it is first
// needed. If the code is being run as part of tests, the regexp compiling will
// happen immediately.
func New(str string) *Regexp {
lr := &Regexp{str: str}
if testutil.InTest {
// In tests, always compile the regexps early.
lr.Regexp()
}
return lr
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/context/api_org.go | internal/context/api_org.go | // Copyright 2016 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package context
import (
"gogs.io/gogs/internal/database"
)
type APIOrganization struct {
Organization *database.User
Team *database.Team
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/context/api.go | internal/context/api.go | // Copyright 2016 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package context
import (
"fmt"
"net/http"
"strings"
"github.com/pkg/errors"
"github.com/unknwon/paginater"
"gopkg.in/macaron.v1"
log "unknwon.dev/clog/v2"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/errutil"
)
type APIContext struct {
*Context // TODO: Reduce to only needed fields instead of full shadow
// Base URL for the version of API endpoints, e.g. https://try.gogs.io/api/v1
BaseURL string
Org *APIOrganization
}
// FIXME: move this constant to github.com/gogs/go-gogs-client
const DocURL = "https://github.com/gogs/docs-api"
// NoContent renders the 204 response.
func (c *APIContext) NoContent() {
c.Status(http.StatusNoContent)
}
// NotFound renders the 404 response.
func (c *APIContext) NotFound() {
c.Status(http.StatusNotFound)
}
// ErrorStatus renders error with given status code.
func (c *APIContext) ErrorStatus(status int, err error) {
c.JSON(status, map[string]string{
"message": err.Error(),
"url": DocURL,
})
}
// Error renders the 500 response.
func (c *APIContext) Error(err error, msg string) {
log.ErrorDepth(4, "%s: %v", msg, err)
c.ErrorStatus(
http.StatusInternalServerError,
errors.New("Something went wrong, please check the server logs for more information."),
)
}
// Errorf renders the 500 response with formatted message.
func (c *APIContext) Errorf(err error, format string, args ...any) {
c.Error(err, fmt.Sprintf(format, args...))
}
// NotFoundOrError use error check function to determine if the error
// is about not found. It responses with 404 status code for not found error,
// or error context description for logging purpose of 500 server error.
func (c *APIContext) NotFoundOrError(err error, msg string) {
if errutil.IsNotFound(err) {
c.NotFound()
return
}
c.Error(err, msg)
}
// SetLinkHeader sets pagination link header by given total number and page size.
func (c *APIContext) SetLinkHeader(total, pageSize int) {
page := paginater.New(total, pageSize, c.QueryInt("page"), 0)
links := make([]string, 0, 4)
if page.HasNext() {
links = append(links, fmt.Sprintf("<%s%s?page=%d>; rel=\"next\"", conf.Server.ExternalURL, c.Req.URL.Path[1:], page.Next()))
}
if !page.IsLast() {
links = append(links, fmt.Sprintf("<%s%s?page=%d>; rel=\"last\"", conf.Server.ExternalURL, c.Req.URL.Path[1:], page.TotalPages()))
}
if !page.IsFirst() {
links = append(links, fmt.Sprintf("<%s%s?page=1>; rel=\"first\"", conf.Server.ExternalURL, c.Req.URL.Path[1:]))
}
if page.HasPrevious() {
links = append(links, fmt.Sprintf("<%s%s?page=%d>; rel=\"prev\"", conf.Server.ExternalURL, c.Req.URL.Path[1:], page.Previous()))
}
if len(links) > 0 {
c.Header().Set("Link", strings.Join(links, ","))
}
}
func APIContexter() macaron.Handler {
return func(ctx *Context) {
c := &APIContext{
Context: ctx,
BaseURL: conf.Server.ExternalURL + "api/v1",
}
ctx.Map(c)
}
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/context/notice.go | internal/context/notice.go | // Copyright 2019 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package context
import (
"os"
"path/filepath"
"github.com/unknwon/com"
log "unknwon.dev/clog/v2"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/markup"
"gogs.io/gogs/internal/tool"
)
// renderNoticeBanner checks if a notice banner file exists and loads the message to display
// on all pages.
func (c *Context) renderNoticeBanner() {
fpath := filepath.Join(conf.CustomDir(), "notice", "banner.md")
if !com.IsExist(fpath) {
return
}
f, err := os.Open(fpath)
if err != nil {
log.Error("Failed to open file %q: %v", fpath, err)
return
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
log.Error("Failed to stat file %q: %v", fpath, err)
return
}
// Limit size to prevent very large messages from breaking pages
var maxSize int64 = 1024
if fi.Size() > maxSize { // Refuse to print very long messages
log.Warn("Notice banner file %q size too large [%d > %d]: refusing to render", fpath, fi.Size(), maxSize)
return
}
buf := make([]byte, maxSize)
n, err := f.Read(buf)
if err != nil {
log.Error("Failed to read file %q: %v", fpath, err)
return
}
buf = buf[:n]
if !tool.IsTextFile(buf) {
log.Warn("Notice banner file %q does not appear to be a text file: aborting", fpath)
return
}
c.Data["ServerNotice"] = string(markup.RawMarkdown(buf, ""))
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/context/repo.go | internal/context/repo.go | // Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package context
import (
"bytes"
"fmt"
"net/url"
"strings"
"github.com/editorconfig/editorconfig-core-go/v2"
"github.com/pkg/errors"
"gopkg.in/macaron.v1"
"github.com/gogs/git-module"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/database"
"gogs.io/gogs/internal/repoutil"
)
type PullRequest struct {
BaseRepo *database.Repository
Allowed bool
SameRepo bool
HeadInfo string // [<user>:]<branch>
}
type Repository struct {
AccessMode database.AccessMode
IsWatching bool
IsViewBranch bool
IsViewTag bool
IsViewCommit bool
Repository *database.Repository
Owner *database.User
Commit *git.Commit
Tag *git.Tag
GitRepo *git.Repository
BranchName string
TagName string
TreePath string
CommitID string
RepoLink string
CloneLink repoutil.CloneLink
CommitsCount int64
Mirror *database.Mirror
PullRequest *PullRequest
}
// IsOwner returns true if current user is the owner of repository.
func (r *Repository) IsOwner() bool {
return r.AccessMode >= database.AccessModeOwner
}
// IsAdmin returns true if current user has admin or higher access of repository.
func (r *Repository) IsAdmin() bool {
return r.AccessMode >= database.AccessModeAdmin
}
// IsWriter returns true if current user has write or higher access of repository.
func (r *Repository) IsWriter() bool {
return r.AccessMode >= database.AccessModeWrite
}
// HasAccess returns true if the current user has at least read access for this repository
func (r *Repository) HasAccess() bool {
return r.AccessMode >= database.AccessModeRead
}
// CanEnableEditor returns true if repository is editable and user has proper access level.
func (r *Repository) CanEnableEditor() bool {
return r.Repository.CanEnableEditor() && r.IsViewBranch && r.IsWriter() && !r.Repository.IsBranchRequirePullRequest(r.BranchName)
}
// Editorconfig returns the ".editorconfig" definition if found in the HEAD of the default branch.
func (r *Repository) Editorconfig() (*editorconfig.Editorconfig, error) {
commit, err := r.GitRepo.BranchCommit(r.Repository.DefaultBranch)
if err != nil {
return nil, errors.Wrapf(err, "get commit of branch %q ", r.Repository.DefaultBranch)
}
entry, err := commit.TreeEntry(".editorconfig")
if err != nil {
return nil, errors.Wrap(err, "get .editorconfig")
}
p, err := entry.Blob().Bytes()
if err != nil {
return nil, errors.Wrap(err, "read .editorconfig")
}
return editorconfig.Parse(bytes.NewReader(p))
}
// MakeURL accepts a string or url.URL as argument and returns escaped URL prepended with repository URL.
func (r *Repository) MakeURL(location any) string {
switch location := location.(type) {
case string:
tempURL := url.URL{
Path: r.RepoLink + "/" + location,
}
return tempURL.String()
case url.URL:
location.Path = r.RepoLink + "/" + location.Path
return location.String()
default:
panic("location type must be either string or url.URL")
}
}
// PullRequestURL returns URL for composing a pull request.
// This function does not check if the repository can actually compose a pull request.
func (r *Repository) PullRequestURL(baseBranch, headBranch string) string {
repoLink := r.RepoLink
if r.PullRequest.BaseRepo != nil {
repoLink = r.PullRequest.BaseRepo.Link()
}
return fmt.Sprintf("%s/compare/%s...%s:%s", repoLink, baseBranch, r.Owner.Name, headBranch)
}
// [0]: issues, [1]: wiki
func RepoAssignment(pages ...bool) macaron.Handler {
return func(c *Context) {
var (
owner *database.User
err error
isIssuesPage bool
isWikiPage bool
)
if len(pages) > 0 {
isIssuesPage = pages[0]
}
if len(pages) > 1 {
isWikiPage = pages[1]
}
ownerName := c.Params(":username")
repoName := strings.TrimSuffix(c.Params(":reponame"), ".git")
// Check if the user is the same as the repository owner
if c.IsLogged && c.User.LowerName == strings.ToLower(ownerName) {
owner = c.User
} else {
owner, err = database.Handle.Users().GetByUsername(c.Req.Context(), ownerName)
if err != nil {
c.NotFoundOrError(err, "get user by name")
return
}
}
c.Repo.Owner = owner
c.Data["Username"] = c.Repo.Owner.Name
repo, err := database.GetRepositoryByName(owner.ID, repoName)
if err != nil {
c.NotFoundOrError(err, "get repository by name")
return
}
c.Repo.Repository = repo
c.Data["RepoName"] = c.Repo.Repository.Name
c.Data["IsBareRepo"] = c.Repo.Repository.IsBare
c.Repo.RepoLink = repo.Link()
c.Data["RepoLink"] = c.Repo.RepoLink
c.Data["RepoRelPath"] = c.Repo.Owner.Name + "/" + c.Repo.Repository.Name
// Admin has super access
if c.IsLogged && c.User.IsAdmin {
c.Repo.AccessMode = database.AccessModeOwner
} else {
c.Repo.AccessMode = database.Handle.Permissions().AccessMode(c.Req.Context(), c.UserID(), repo.ID,
database.AccessModeOptions{
OwnerID: repo.OwnerID,
Private: repo.IsPrivate,
},
)
}
// If the authenticated user has no direct access, see if the repository is a fork
// and whether the user has access to the base repository.
if c.Repo.AccessMode == database.AccessModeNone && repo.BaseRepo != nil {
mode := database.Handle.Permissions().AccessMode(c.Req.Context(), c.UserID(), repo.BaseRepo.ID,
database.AccessModeOptions{
OwnerID: repo.BaseRepo.OwnerID,
Private: repo.BaseRepo.IsPrivate,
},
)
// Users shouldn't have indirect access level higher than write.
if mode > database.AccessModeWrite {
mode = database.AccessModeWrite
}
c.Repo.AccessMode = mode
}
// Check access
if c.Repo.AccessMode == database.AccessModeNone {
// Redirect to any accessible page if not yet on it
if repo.IsPartialPublic() &&
(!(isIssuesPage || isWikiPage) ||
(isIssuesPage && !repo.CanGuestViewIssues()) ||
(isWikiPage && !repo.CanGuestViewWiki())) {
switch {
case repo.CanGuestViewIssues():
c.Redirect(repo.Link() + "/issues")
case repo.CanGuestViewWiki():
c.Redirect(repo.Link() + "/wiki")
default:
c.NotFound()
}
return
}
// Response 404 if user is on completely private repository or possible accessible page but owner doesn't enabled
if !repo.IsPartialPublic() ||
(isIssuesPage && !repo.CanGuestViewIssues()) ||
(isWikiPage && !repo.CanGuestViewWiki()) {
c.NotFound()
return
}
c.Repo.Repository.EnableIssues = repo.CanGuestViewIssues()
c.Repo.Repository.EnableWiki = repo.CanGuestViewWiki()
}
if repo.IsMirror {
c.Repo.Mirror, err = database.GetMirrorByRepoID(repo.ID)
if err != nil {
c.Error(err, "get mirror by repository ID")
return
}
c.Data["MirrorEnablePrune"] = c.Repo.Mirror.EnablePrune
c.Data["MirrorInterval"] = c.Repo.Mirror.Interval
c.Data["Mirror"] = c.Repo.Mirror
}
gitRepo, err := git.Open(database.RepoPath(ownerName, repoName))
if err != nil {
c.Error(err, "open repository")
return
}
c.Repo.GitRepo = gitRepo
tags, err := c.Repo.GitRepo.Tags()
if err != nil {
c.Error(err, "get tags")
return
}
c.Data["Tags"] = tags
c.Repo.Repository.NumTags = len(tags)
c.Data["Title"] = owner.Name + "/" + repo.Name
c.Data["Repository"] = repo
c.Data["Owner"] = c.Repo.Repository.Owner
c.Data["IsRepositoryOwner"] = c.Repo.IsOwner()
c.Data["IsRepositoryAdmin"] = c.Repo.IsAdmin()
c.Data["IsRepositoryWriter"] = c.Repo.IsWriter()
c.Data["DisableSSH"] = conf.SSH.Disabled
c.Data["DisableHTTP"] = conf.Repository.DisableHTTPGit
c.Data["CloneLink"] = repo.CloneLink()
c.Data["WikiCloneLink"] = repo.WikiCloneLink()
if c.IsLogged {
c.Data["IsWatchingRepo"] = database.IsWatching(c.User.ID, repo.ID)
c.Data["IsStaringRepo"] = database.IsStaring(c.User.ID, repo.ID)
}
// repo is bare and display enable
if c.Repo.Repository.IsBare {
return
}
c.Data["TagName"] = c.Repo.TagName
branches, err := c.Repo.GitRepo.Branches()
if err != nil {
c.Error(err, "get branches")
return
}
c.Data["Branches"] = branches
c.Data["BranchCount"] = len(branches)
// If not branch selected, try default one.
// If default branch doesn't exists, fall back to some other branch.
if c.Repo.BranchName == "" {
if len(c.Repo.Repository.DefaultBranch) > 0 && gitRepo.HasBranch(c.Repo.Repository.DefaultBranch) {
c.Repo.BranchName = c.Repo.Repository.DefaultBranch
} else if len(branches) > 0 {
c.Repo.BranchName = branches[0]
}
}
c.Data["BranchName"] = c.Repo.BranchName
c.Data["CommitID"] = c.Repo.CommitID
c.Data["IsGuest"] = !c.Repo.HasAccess()
}
}
// RepoRef handles repository reference name including those contain `/`.
func RepoRef() macaron.Handler {
return func(c *Context) {
// Empty repository does not have reference information.
if c.Repo.Repository.IsBare {
return
}
var (
refName string
err error
)
// For API calls.
if c.Repo.GitRepo == nil {
repoPath := database.RepoPath(c.Repo.Owner.Name, c.Repo.Repository.Name)
c.Repo.GitRepo, err = git.Open(repoPath)
if err != nil {
c.Error(err, "open repository")
return
}
}
// Get default branch.
if c.Params("*") == "" {
refName = c.Repo.Repository.DefaultBranch
if !c.Repo.GitRepo.HasBranch(refName) {
branches, err := c.Repo.GitRepo.Branches()
if err != nil {
c.Error(err, "get branches")
return
}
refName = branches[0]
}
c.Repo.Commit, err = c.Repo.GitRepo.BranchCommit(refName)
if err != nil {
c.Error(err, "get branch commit")
return
}
c.Repo.CommitID = c.Repo.Commit.ID.String()
c.Repo.IsViewBranch = true
} else {
hasMatched := false
parts := strings.Split(c.Params("*"), "/")
for i, part := range parts {
refName = strings.TrimPrefix(refName+"/"+part, "/")
if c.Repo.GitRepo.HasBranch(refName) ||
c.Repo.GitRepo.HasTag(refName) {
if i < len(parts)-1 {
c.Repo.TreePath = strings.Join(parts[i+1:], "/")
}
hasMatched = true
break
}
}
if !hasMatched && len(parts[0]) == 40 {
refName = parts[0]
c.Repo.TreePath = strings.Join(parts[1:], "/")
}
if c.Repo.GitRepo.HasBranch(refName) {
c.Repo.IsViewBranch = true
c.Repo.Commit, err = c.Repo.GitRepo.BranchCommit(refName)
if err != nil {
c.Error(err, "get branch commit")
return
}
c.Repo.CommitID = c.Repo.Commit.ID.String()
} else if c.Repo.GitRepo.HasTag(refName) {
c.Repo.IsViewTag = true
c.Repo.Commit, err = c.Repo.GitRepo.TagCommit(refName)
if err != nil {
c.Error(err, "get tag commit")
return
}
c.Repo.CommitID = c.Repo.Commit.ID.String()
} else if len(refName) == 40 {
c.Repo.IsViewCommit = true
c.Repo.CommitID = refName
c.Repo.Commit, err = c.Repo.GitRepo.CatFileCommit(refName)
if err != nil {
c.NotFound()
return
}
} else {
c.NotFound()
return
}
}
c.Repo.BranchName = refName
c.Data["BranchName"] = c.Repo.BranchName
c.Data["CommitID"] = c.Repo.CommitID
c.Data["TreePath"] = c.Repo.TreePath
c.Data["IsViewBranch"] = c.Repo.IsViewBranch
c.Data["IsViewTag"] = c.Repo.IsViewTag
c.Data["IsViewCommit"] = c.Repo.IsViewCommit
// People who have push access or have forked repository can propose a new pull request.
if c.Repo.IsWriter() || (c.IsLogged && database.Handle.Repositories().HasForkedBy(c.Req.Context(), c.Repo.Repository.ID, c.User.ID)) {
// Pull request is allowed if this is a fork repository
// and base repository accepts pull requests.
if c.Repo.Repository.BaseRepo != nil {
if c.Repo.Repository.BaseRepo.AllowsPulls() {
c.Repo.PullRequest.Allowed = true
// In-repository pull requests has higher priority than cross-repository if user is viewing
// base repository and 1) has write access to it 2) has forked it.
if c.Repo.IsWriter() {
c.Data["BaseRepo"] = c.Repo.Repository.BaseRepo
c.Repo.PullRequest.BaseRepo = c.Repo.Repository.BaseRepo
c.Repo.PullRequest.HeadInfo = c.Repo.Owner.Name + ":" + c.Repo.BranchName
} else {
c.Data["BaseRepo"] = c.Repo.Repository
c.Repo.PullRequest.BaseRepo = c.Repo.Repository
c.Repo.PullRequest.HeadInfo = c.User.Name + ":" + c.Repo.BranchName
}
}
} else {
// Or, this is repository accepts pull requests between branches.
if c.Repo.Repository.AllowsPulls() {
c.Data["BaseRepo"] = c.Repo.Repository
c.Repo.PullRequest.BaseRepo = c.Repo.Repository
c.Repo.PullRequest.Allowed = true
c.Repo.PullRequest.SameRepo = true
c.Repo.PullRequest.HeadInfo = c.Repo.BranchName
}
}
}
c.Data["PullRequestCtx"] = c.Repo.PullRequest
}
}
func RequireRepoAdmin() macaron.Handler {
return func(c *Context) {
if !c.IsLogged || (!c.Repo.IsAdmin() && !c.User.IsAdmin) {
c.NotFound()
return
}
}
}
func RequireRepoWriter() macaron.Handler {
return func(c *Context) {
if !c.IsLogged || (!c.Repo.IsWriter() && !c.User.IsAdmin) {
c.NotFound()
return
}
}
}
// GitHookService checks if repository Git hooks service has been enabled.
func GitHookService() macaron.Handler {
return func(c *Context) {
if !c.User.CanEditGitHook() {
c.NotFound()
return
}
}
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/context/store.go | internal/context/store.go | package context
import (
"context"
"gogs.io/gogs/internal/database"
)
// Store is the data layer carrier for context middleware. This interface is
// meant to abstract away and limit the exposure of the underlying data layer to
// the handler through a thin-wrapper.
type Store interface {
// GetAccessTokenBySHA1 returns the access token with given SHA1. It returns
// database.ErrAccessTokenNotExist when not found.
GetAccessTokenBySHA1(ctx context.Context, sha1 string) (*database.AccessToken, error)
// TouchAccessTokenByID updates the updated time of the given access token to
// the current time.
TouchAccessTokenByID(ctx context.Context, id int64) error
// GetUserByID returns the user with given ID. It returns
// database.ErrUserNotExist when not found.
GetUserByID(ctx context.Context, id int64) (*database.User, error)
// GetUserByUsername returns the user with given username. It returns
// database.ErrUserNotExist when not found.
GetUserByUsername(ctx context.Context, username string) (*database.User, error)
// CreateUser creates a new user and persists to database. It returns
// database.ErrNameNotAllowed if the given name or pattern of the name is not
// allowed as a username, or database.ErrUserAlreadyExist when a user with same
// name already exists, or database.ErrEmailAlreadyUsed if the email has been
// verified by another user.
CreateUser(ctx context.Context, username, email string, opts database.CreateUserOptions) (*database.User, error)
// AuthenticateUser validates username and password via given login source ID.
// It returns database.ErrUserNotExist when the user was not found.
//
// When the "loginSourceID" is negative, it aborts the process and returns
// database.ErrUserNotExist if the user was not found in the database.
//
// When the "loginSourceID" is non-negative, it returns
// database.ErrLoginSourceMismatch if the user has different login source ID
// than the "loginSourceID".
//
// When the "loginSourceID" is positive, it tries to authenticate via given
// login source and creates a new user when not yet exists in the database.
AuthenticateUser(ctx context.Context, login, password string, loginSourceID int64) (*database.User, error)
}
type store struct{}
// NewStore returns a new Store using the global database handle.
func NewStore() Store {
return &store{}
}
func (*store) GetAccessTokenBySHA1(ctx context.Context, sha1 string) (*database.AccessToken, error) {
return database.Handle.AccessTokens().GetBySHA1(ctx, sha1)
}
func (*store) TouchAccessTokenByID(ctx context.Context, id int64) error {
return database.Handle.AccessTokens().Touch(ctx, id)
}
func (*store) GetUserByID(ctx context.Context, id int64) (*database.User, error) {
return database.Handle.Users().GetByID(ctx, id)
}
func (*store) GetUserByUsername(ctx context.Context, username string) (*database.User, error) {
return database.Handle.Users().GetByUsername(ctx, username)
}
func (*store) CreateUser(ctx context.Context, username, email string, opts database.CreateUserOptions) (*database.User, error) {
return database.Handle.Users().Create(ctx, username, email, opts)
}
func (*store) AuthenticateUser(ctx context.Context, login, password string, loginSourceID int64) (*database.User, error) {
return database.Handle.Users().Authenticate(ctx, login, password, loginSourceID)
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/context/auth.go | internal/context/auth.go | // Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package context
import (
"context"
"net/http"
"net/url"
"strings"
"github.com/go-macaron/csrf"
"github.com/go-macaron/session"
"github.com/pkg/errors"
gouuid "github.com/satori/go.uuid"
"gopkg.in/macaron.v1"
log "unknwon.dev/clog/v2"
"gogs.io/gogs/internal/auth"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/database"
"gogs.io/gogs/internal/tool"
)
type ToggleOptions struct {
SignInRequired bool
SignOutRequired bool
AdminRequired bool
DisableCSRF bool
}
func Toggle(options *ToggleOptions) macaron.Handler {
return func(c *Context) {
// Cannot view any page before installation.
if !conf.Security.InstallLock {
c.RedirectSubpath("/install")
return
}
// Check prohibit login users.
if c.IsLogged && c.User.ProhibitLogin {
c.Data["Title"] = c.Tr("auth.prohibit_login")
c.Success("user/auth/prohibit_login")
return
}
// Check non-logged users landing page.
if !c.IsLogged && c.Req.RequestURI == "/" && conf.Server.LandingURL != "/" {
c.RedirectSubpath(conf.Server.LandingURL)
return
}
// Redirect to dashboard if user tries to visit any non-login page.
if options.SignOutRequired && c.IsLogged && c.Req.RequestURI != "/" {
c.RedirectSubpath("/")
return
}
if !options.SignOutRequired && !options.DisableCSRF && c.Req.Method == "POST" && !isAPIPath(c.Req.URL.Path) {
csrf.Validate(c.Context, c.csrf)
if c.Written() {
return
}
}
if options.SignInRequired {
if !c.IsLogged {
// Restrict API calls with error message.
if isAPIPath(c.Req.URL.Path) {
c.JSON(http.StatusForbidden, map[string]string{
"message": "Only authenticated user is allowed to call APIs.",
})
return
}
c.SetCookie("redirect_to", url.QueryEscape(conf.Server.Subpath+c.Req.RequestURI), 0, conf.Server.Subpath)
c.RedirectSubpath("/user/login")
return
} else if !c.User.IsActive && conf.Auth.RequireEmailConfirmation {
c.Title("auth.active_your_account")
c.Success("user/auth/activate")
return
}
}
// Redirect to log in page if auto-signin info is provided and has not signed in.
if !options.SignOutRequired && !c.IsLogged && !isAPIPath(c.Req.URL.Path) &&
len(c.GetCookie(conf.Security.CookieUsername)) > 0 {
c.SetCookie("redirect_to", url.QueryEscape(conf.Server.Subpath+c.Req.RequestURI), 0, conf.Server.Subpath)
c.RedirectSubpath("/user/login")
return
}
if options.AdminRequired {
if !c.User.IsAdmin {
c.Status(http.StatusForbidden)
return
}
c.PageIs("Admin")
}
}
}
func isAPIPath(url string) bool {
return strings.HasPrefix(url, "/api/")
}
type AuthStore interface {
// GetAccessTokenBySHA1 returns the access token with given SHA1. It returns
// database.ErrAccessTokenNotExist when not found.
GetAccessTokenBySHA1(ctx context.Context, sha1 string) (*database.AccessToken, error)
// TouchAccessTokenByID updates the updated time of the given access token to
// the current time.
TouchAccessTokenByID(ctx context.Context, id int64) error
// GetUserByID returns the user with given ID. It returns
// database.ErrUserNotExist when not found.
GetUserByID(ctx context.Context, id int64) (*database.User, error)
// GetUserByUsername returns the user with given username. It returns
// database.ErrUserNotExist when not found.
GetUserByUsername(ctx context.Context, username string) (*database.User, error)
// CreateUser creates a new user and persists to database. It returns
// database.ErrNameNotAllowed if the given name or pattern of the name is not
// allowed as a username, or database.ErrUserAlreadyExist when a user with same
// name already exists, or database.ErrEmailAlreadyUsed if the email has been
// verified by another user.
CreateUser(ctx context.Context, username, email string, opts database.CreateUserOptions) (*database.User, error)
// AuthenticateUser validates username and password via given login source ID.
// It returns database.ErrUserNotExist when the user was not found.
//
// When the "loginSourceID" is negative, it aborts the process and returns
// database.ErrUserNotExist if the user was not found in the database.
//
// When the "loginSourceID" is non-negative, it returns
// database.ErrLoginSourceMismatch if the user has different login source ID
// than the "loginSourceID".
//
// When the "loginSourceID" is positive, it tries to authenticate via given
// login source and creates a new user when not yet exists in the database.
AuthenticateUser(ctx context.Context, login, password string, loginSourceID int64) (*database.User, error)
}
// authenticatedUserID returns the ID of the authenticated user, along with a bool value
// which indicates whether the user uses token authentication.
func authenticatedUserID(store AuthStore, c *macaron.Context, sess session.Store) (_ int64, isTokenAuth bool) {
if !database.HasEngine {
return 0, false
}
// Check access token.
if isAPIPath(c.Req.URL.Path) {
tokenSHA := c.Query("token")
if len(tokenSHA) <= 0 {
tokenSHA = c.Query("access_token")
}
if tokenSHA == "" {
// Well, check with header again.
auHead := c.Req.Header.Get("Authorization")
if len(auHead) > 0 {
auths := strings.Fields(auHead)
if len(auths) == 2 && auths[0] == "token" {
tokenSHA = auths[1]
}
}
}
// Let's see if token is valid.
if len(tokenSHA) > 0 {
t, err := store.GetAccessTokenBySHA1(c.Req.Context(), tokenSHA)
if err != nil {
if !database.IsErrAccessTokenNotExist(err) {
log.Error("GetAccessTokenBySHA: %v", err)
}
return 0, false
}
if err = store.TouchAccessTokenByID(c.Req.Context(), t.ID); err != nil {
log.Error("Failed to touch access token: %v", err)
}
return t.UserID, true
}
}
uid := sess.Get("uid")
if uid == nil {
return 0, false
}
if id, ok := uid.(int64); ok {
_, err := store.GetUserByID(c.Req.Context(), id)
if err != nil {
if !database.IsErrUserNotExist(err) {
log.Error("Failed to get user by ID: %v", err)
}
return 0, false
}
return id, false
}
return 0, false
}
// authenticatedUser returns the user object of the authenticated user, along with two bool values
// which indicate whether the user uses HTTP Basic Authentication or token authentication respectively.
func authenticatedUser(store AuthStore, ctx *macaron.Context, sess session.Store) (_ *database.User, isBasicAuth, isTokenAuth bool) {
if !database.HasEngine {
return nil, false, false
}
uid, isTokenAuth := authenticatedUserID(store, ctx, sess)
if uid <= 0 {
if conf.Auth.EnableReverseProxyAuthentication {
webAuthUser := ctx.Req.Header.Get(conf.Auth.ReverseProxyAuthenticationHeader)
if len(webAuthUser) > 0 {
user, err := store.GetUserByUsername(ctx.Req.Context(), webAuthUser)
if err != nil {
if !database.IsErrUserNotExist(err) {
log.Error("Failed to get user by name: %v", err)
return nil, false, false
}
// Check if enabled auto-registration.
if conf.Auth.EnableReverseProxyAutoRegistration {
user, err = store.CreateUser(
ctx.Req.Context(),
webAuthUser,
gouuid.NewV4().String()+"@localhost",
database.CreateUserOptions{
Activated: true,
},
)
if err != nil {
log.Error("Failed to create user %q: %v", webAuthUser, err)
return nil, false, false
}
}
}
return user, false, false
}
}
// Check with basic auth.
baHead := ctx.Req.Header.Get("Authorization")
if len(baHead) > 0 {
auths := strings.Fields(baHead)
if len(auths) == 2 && auths[0] == "Basic" {
uname, passwd, _ := tool.BasicAuthDecode(auths[1])
u, err := store.AuthenticateUser(ctx.Req.Context(), uname, passwd, -1)
if err != nil {
if !auth.IsErrBadCredentials(err) {
log.Error("Failed to authenticate user: %v", err)
}
return nil, false, false
}
return u, true, false
}
}
return nil, false, false
}
u, err := store.GetUserByID(ctx.Req.Context(), uid)
if err != nil {
log.Error("GetUserByID: %v", err)
return nil, false, false
}
return u, false, isTokenAuth
}
// AuthenticateByToken attempts to authenticate a user by the given access
// token. It returns database.ErrAccessTokenNotExist when the access token does not
// exist.
func AuthenticateByToken(store AuthStore, ctx context.Context, token string) (*database.User, error) {
t, err := store.GetAccessTokenBySHA1(ctx, token)
if err != nil {
return nil, errors.Wrap(err, "get access token by SHA1")
}
if err = store.TouchAccessTokenByID(ctx, t.ID); err != nil {
// NOTE: There is no need to fail the auth flow if we can't touch the token.
log.Error("Failed to touch access token [id: %d]: %v", t.ID, err)
}
user, err := store.GetUserByID(ctx, t.UserID)
if err != nil {
return nil, errors.Wrapf(err, "get user by ID [user_id: %d]", t.UserID)
}
return user, nil
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/context/context.go | internal/context/context.go | // Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package context
import (
"fmt"
"io"
"net/http"
"strings"
"time"
"github.com/go-macaron/cache"
"github.com/go-macaron/csrf"
"github.com/go-macaron/i18n"
"github.com/go-macaron/session"
"gopkg.in/macaron.v1"
log "unknwon.dev/clog/v2"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/database"
"gogs.io/gogs/internal/errutil"
"gogs.io/gogs/internal/form"
"gogs.io/gogs/internal/lazyregexp"
"gogs.io/gogs/internal/template"
)
// Context represents context of a request.
type Context struct {
*macaron.Context
Cache cache.Cache
csrf csrf.CSRF
Flash *session.Flash
Session session.Store
Link string // Current request URL
User *database.User
IsLogged bool
IsBasicAuth bool
IsTokenAuth bool
Repo *Repository
Org *Organization
}
// RawTitle sets the "Title" field in template data.
func (c *Context) RawTitle(title string) {
c.Data["Title"] = title
}
// Title localizes the "Title" field in template data.
func (c *Context) Title(locale string) {
c.RawTitle(c.Tr(locale))
}
// PageIs sets "PageIsxxx" field in template data.
func (c *Context) PageIs(name string) {
c.Data["PageIs"+name] = true
}
// Require sets "Requirexxx" field in template data.
func (c *Context) Require(name string) {
c.Data["Require"+name] = true
}
func (c *Context) RequireHighlightJS() {
c.Require("HighlightJS")
}
func (c *Context) RequireSimpleMDE() {
c.Require("SimpleMDE")
}
func (c *Context) RequireAutosize() {
c.Require("Autosize")
}
func (c *Context) RequireDropzone() {
c.Require("Dropzone")
}
// FormErr sets "Err_xxx" field in template data.
func (c *Context) FormErr(names ...string) {
for i := range names {
c.Data["Err_"+names[i]] = true
}
}
// UserID returns ID of current logged in user.
// It returns 0 if visitor is anonymous.
func (c *Context) UserID() int64 {
if !c.IsLogged {
return 0
}
return c.User.ID
}
func (c *Context) GetErrMsg() string {
return c.Data["ErrorMsg"].(string)
}
// HasError returns true if error occurs in form validation.
func (c *Context) HasError() bool {
hasErr, ok := c.Data["HasError"]
if !ok {
return false
}
c.Flash.ErrorMsg = c.Data["ErrorMsg"].(string)
c.Data["Flash"] = c.Flash
return hasErr.(bool)
}
// HasValue returns true if value of given name exists.
func (c *Context) HasValue(name string) bool {
_, ok := c.Data[name]
return ok
}
// HTML responses template with given status.
func (c *Context) HTML(status int, name string) {
log.Trace("Template: %s", name)
c.Context.HTML(status, name)
}
// Success responses template with status http.StatusOK.
func (c *Context) Success(name string) {
c.HTML(http.StatusOK, name)
}
// JSONSuccess responses JSON with status http.StatusOK.
func (c *Context) JSONSuccess(data any) {
c.JSON(http.StatusOK, data)
}
// RawRedirect simply calls underlying Redirect method with no escape.
func (c *Context) RawRedirect(location string, status ...int) {
c.Context.Redirect(location, status...)
}
// Redirect responses redirection with given location and status.
// It escapes special characters in the location string.
func (c *Context) Redirect(location string, status ...int) {
c.Context.Redirect(template.EscapePound(location), status...)
}
// RedirectSubpath responses redirection with given location and status.
// It prepends setting.Server.Subpath to the location string.
func (c *Context) RedirectSubpath(location string, status ...int) {
c.Redirect(conf.Server.Subpath+location, status...)
}
// RenderWithErr used for page has form validation but need to prompt error to users.
func (c *Context) RenderWithErr(msg, tpl string, f any) {
if f != nil {
form.Assign(f, c.Data)
}
c.Flash.ErrorMsg = msg
c.Data["Flash"] = c.Flash
c.HTML(http.StatusOK, tpl)
}
// NotFound renders the 404 page.
func (c *Context) NotFound() {
c.Title("status.page_not_found")
c.HTML(http.StatusNotFound, fmt.Sprintf("status/%d", http.StatusNotFound))
}
// Error renders the 500 page.
func (c *Context) Error(err error, msg string) {
log.ErrorDepth(4, "%s: %v", msg, err)
c.Title("status.internal_server_error")
// Only in non-production mode or admin can see the actual error message.
if !conf.IsProdMode() || (c.IsLogged && c.User.IsAdmin) {
c.Data["ErrorMsg"] = err
}
c.HTML(http.StatusInternalServerError, fmt.Sprintf("status/%d", http.StatusInternalServerError))
}
// Errorf renders the 500 response with formatted message.
func (c *Context) Errorf(err error, format string, args ...any) {
c.Error(err, fmt.Sprintf(format, args...))
}
// NotFoundOrError responses with 404 page for not found error and 500 page otherwise.
func (c *Context) NotFoundOrError(err error, msg string) {
if errutil.IsNotFound(err) {
c.NotFound()
return
}
c.Error(err, msg)
}
// NotFoundOrErrorf is same as NotFoundOrError but with formatted message.
func (c *Context) NotFoundOrErrorf(err error, format string, args ...any) {
c.NotFoundOrError(err, fmt.Sprintf(format, args...))
}
func (c *Context) PlainText(status int, msg string) {
c.Render.PlainText(status, []byte(msg))
}
func (c *Context) ServeContent(name string, r io.ReadSeeker, params ...any) {
modtime := time.Now()
for _, p := range params {
switch v := p.(type) {
case time.Time:
modtime = v
}
}
c.Resp.Header().Set("Content-Description", "File Transfer")
c.Resp.Header().Set("Content-Type", "application/octet-stream")
c.Resp.Header().Set("Content-Disposition", "attachment; filename="+name)
c.Resp.Header().Set("Content-Transfer-Encoding", "binary")
c.Resp.Header().Set("Expires", "0")
c.Resp.Header().Set("Cache-Control", "must-revalidate")
c.Resp.Header().Set("Pragma", "public")
http.ServeContent(c.Resp, c.Req.Request, name, modtime, r)
}
// csrfTokenExcludePattern matches characters that are not used for generating
// CSRF tokens, see all possible characters at
// https://github.com/go-macaron/csrf/blob/5d38f39de352972063d1ef026fc477283841bb9b/csrf.go#L148.
var csrfTokenExcludePattern = lazyregexp.New(`[^a-zA-Z0-9-_].*`)
// Contexter initializes a classic context for a request.
func Contexter(store Store) macaron.Handler {
return func(ctx *macaron.Context, l i18n.Locale, cache cache.Cache, sess session.Store, f *session.Flash, x csrf.CSRF) {
c := &Context{
Context: ctx,
Cache: cache,
csrf: x,
Flash: f,
Session: sess,
Link: conf.Server.Subpath + strings.TrimSuffix(ctx.Req.URL.Path, "/"),
Repo: &Repository{
PullRequest: &PullRequest{},
},
Org: &Organization{},
}
c.Data["Link"] = template.EscapePound(c.Link)
c.Data["PageStartTime"] = time.Now()
if len(conf.HTTP.AccessControlAllowOrigin) > 0 {
c.Header().Set("Access-Control-Allow-Origin", conf.HTTP.AccessControlAllowOrigin)
c.Header().Set("Access-Control-Allow-Credentials", "true")
c.Header().Set("Access-Control-Max-Age", "3600")
c.Header().Set("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With")
}
// Get user from session or header when possible
c.User, c.IsBasicAuth, c.IsTokenAuth = authenticatedUser(store, c.Context, c.Session)
if c.User != nil {
c.IsLogged = true
c.Data["IsLogged"] = c.IsLogged
c.Data["LoggedUser"] = c.User
c.Data["LoggedUserID"] = c.User.ID
c.Data["LoggedUserName"] = c.User.Name
c.Data["IsAdmin"] = c.User.IsAdmin
} else {
c.Data["LoggedUserID"] = 0
c.Data["LoggedUserName"] = ""
}
// If request sends files, parse them here otherwise the Query() can't be parsed and the CsrfToken will be invalid.
if c.Req.Method == "POST" && strings.Contains(c.Req.Header.Get("Content-Type"), "multipart/form-data") {
if err := c.Req.ParseMultipartForm(conf.Attachment.MaxSize << 20); err != nil && !strings.Contains(err.Error(), "EOF") { // 32MB max size
c.Error(err, "parse multipart form")
return
}
}
// 🚨 SECURITY: Prevent XSS from injected CSRF cookie by stripping all
// characters that are not used for generating CSRF tokens, see
// https://github.com/gogs/gogs/issues/6953 for details.
csrfToken := csrfTokenExcludePattern.ReplaceAllString(x.GetToken(), "")
c.Data["CSRFToken"] = csrfToken
c.Data["CSRFTokenHTML"] = template.Safe(`<input type="hidden" name="_csrf" value="` + csrfToken + `">`)
log.Trace("Session ID: %s", sess.ID())
log.Trace("CSRF Token: %v", c.Data["CSRFToken"])
c.Data["ShowRegistrationButton"] = !conf.Auth.DisableRegistration
c.Data["ShowFooterBranding"] = conf.Other.ShowFooterBranding
c.renderNoticeBanner()
// 🚨 SECURITY: Prevent MIME type sniffing in some browsers,
// see https://github.com/gogs/gogs/issues/5397 for details.
c.Header().Set("X-Content-Type-Options", "nosniff")
c.Header().Set("X-Frame-Options", "deny")
ctx.Map(c)
}
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/context/user.go | internal/context/user.go | // Copyright 2018 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package context
import (
"gopkg.in/macaron.v1"
"gogs.io/gogs/internal/database"
)
// ParamsUser is the wrapper type of the target user defined by URL parameter, namely ':username'.
type ParamsUser struct {
*database.User
}
// InjectParamsUser returns a handler that retrieves target user based on URL parameter ':username',
// and injects it as *ParamsUser.
func InjectParamsUser() macaron.Handler {
return func(c *Context) {
user, err := database.Handle.Users().GetByUsername(c.Req.Context(), c.Params(":username"))
if err != nil {
c.NotFoundOrError(err, "get user by name")
return
}
c.Map(&ParamsUser{user})
}
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/context/go_get.go | internal/context/go_get.go | package context
import (
"net/http"
"path"
"strings"
"github.com/unknwon/com"
"gopkg.in/macaron.v1"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/database"
"gogs.io/gogs/internal/repoutil"
)
// ServeGoGet does quick responses for appropriate go-get meta with status OK
// regardless of whether the user has access to the repository, or the repository
// does exist at all. This is particular a workaround for "go get" command which
// does not respect .netrc file.
func ServeGoGet() macaron.Handler {
return func(c *macaron.Context) {
if c.Query("go-get") != "1" {
return
}
ownerName := c.Params(":username")
repoName := c.Params(":reponame")
branchName := "master"
owner, err := database.Handle.Users().GetByUsername(c.Req.Context(), ownerName)
if err == nil {
repo, err := database.Handle.Repositories().GetByName(c.Req.Context(), owner.ID, repoName)
if err == nil && repo.DefaultBranch != "" {
branchName = repo.DefaultBranch
}
}
prefix := conf.Server.ExternalURL + path.Join(ownerName, repoName, "src", branchName)
insecureFlag := ""
if !strings.HasPrefix(conf.Server.ExternalURL, "https://") {
insecureFlag = "--insecure "
}
c.PlainText(http.StatusOK, []byte(com.Expand(`<!doctype html>
<html>
<head>
<meta name="go-import" content="{GoGetImport} git {CloneLink}">
<meta name="go-source" content="{GoGetImport} _ {GoDocDirectory} {GoDocFile}">
</head>
<body>
go get {InsecureFlag}{GoGetImport}
</body>
</html>
`,
map[string]string{
"GoGetImport": path.Join(conf.Server.URL.Host, conf.Server.Subpath, ownerName, repoName),
"CloneLink": repoutil.HTTPSCloneURL(ownerName, repoName),
"GoDocDirectory": prefix + "{/dir}",
"GoDocFile": prefix + "{/dir}/{file}#L{line}",
"InsecureFlag": insecureFlag,
},
)))
}
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/context/org.go | internal/context/org.go | // Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package context
import (
"strings"
"gopkg.in/macaron.v1"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/database"
)
type Organization struct {
IsOwner bool
IsMember bool
IsTeamMember bool // Is member of team.
IsTeamAdmin bool // In owner team or team that has admin permission level.
Organization *database.User
OrgLink string
Team *database.Team
}
func HandleOrgAssignment(c *Context, args ...bool) {
var (
requireMember bool
requireOwner bool
requireTeamMember bool
requireTeamAdmin bool
)
if len(args) >= 1 {
requireMember = args[0]
}
if len(args) >= 2 {
requireOwner = args[1]
}
if len(args) >= 3 {
requireTeamMember = args[2]
}
if len(args) >= 4 {
requireTeamAdmin = args[3]
}
orgName := c.Params(":org")
var err error
c.Org.Organization, err = database.Handle.Users().GetByUsername(c.Req.Context(), orgName)
if err != nil {
c.NotFoundOrError(err, "get organization by name")
return
}
org := c.Org.Organization
c.Data["Org"] = org
// Force redirection when username is actually a user.
if !org.IsOrganization() {
c.Redirect("/" + org.Name)
return
}
// Admin has super access.
if c.IsLogged && c.User.IsAdmin {
c.Org.IsOwner = true
c.Org.IsMember = true
c.Org.IsTeamMember = true
c.Org.IsTeamAdmin = true
} else if c.IsLogged {
c.Org.IsOwner = org.IsOwnedBy(c.User.ID)
if c.Org.IsOwner {
c.Org.IsMember = true
c.Org.IsTeamMember = true
c.Org.IsTeamAdmin = true
} else if org.IsOrgMember(c.User.ID) {
c.Org.IsMember = true
}
} else {
// Fake data.
c.Data["SignedUser"] = &database.User{}
}
if (requireMember && !c.Org.IsMember) ||
(requireOwner && !c.Org.IsOwner) {
c.NotFound()
return
}
c.Data["IsOrganizationOwner"] = c.Org.IsOwner
c.Data["IsOrganizationMember"] = c.Org.IsMember
c.Org.OrgLink = conf.Server.Subpath + "/org/" + org.Name
c.Data["OrgLink"] = c.Org.OrgLink
// Team.
if c.Org.IsMember {
if c.Org.IsOwner {
if err := org.GetTeams(); err != nil {
c.Error(err, "get teams")
return
}
} else {
org.Teams, err = org.GetUserTeams(c.User.ID)
if err != nil {
c.Error(err, "get user teams")
return
}
}
}
teamName := c.Params(":team")
if len(teamName) > 0 {
teamExists := false
for _, team := range org.Teams {
if team.LowerName == strings.ToLower(teamName) {
teamExists = true
c.Org.Team = team
c.Org.IsTeamMember = true
c.Data["Team"] = c.Org.Team
break
}
}
if !teamExists {
c.NotFound()
return
}
c.Data["IsTeamMember"] = c.Org.IsTeamMember
if requireTeamMember && !c.Org.IsTeamMember {
c.NotFound()
return
}
c.Org.IsTeamAdmin = c.Org.Team.IsOwnerTeam() || c.Org.Team.Authorize >= database.AccessModeAdmin
c.Data["IsTeamAdmin"] = c.Org.IsTeamAdmin
if requireTeamAdmin && !c.Org.IsTeamAdmin {
c.NotFound()
return
}
}
}
func OrgAssignment(args ...bool) macaron.Handler {
return func(c *Context) {
HandleOrgAssignment(c, args...)
}
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.