diff options
-rw-r--r-- | cmd/serve.go | 54 | ||||
-rw-r--r-- | models/access.go | 188 | ||||
-rw-r--r-- | models/action.go | 42 | ||||
-rw-r--r-- | models/issue.go | 21 | ||||
-rw-r--r-- | models/migrations/migrations.go | 274 | ||||
-rw-r--r-- | models/models.go | 36 | ||||
-rw-r--r-- | models/org.go | 329 | ||||
-rw-r--r-- | models/repo.go | 638 | ||||
-rw-r--r-- | models/user.go | 73 | ||||
-rw-r--r-- | modules/middleware/org.go | 2 | ||||
-rw-r--r-- | modules/middleware/repo.go | 149 | ||||
-rw-r--r-- | modules/setting/setting.go | 5 | ||||
-rw-r--r-- | routers/api/v1/repo.go | 21 | ||||
-rw-r--r-- | routers/org/teams.go | 16 | ||||
-rw-r--r-- | routers/repo/http.go | 10 | ||||
-rw-r--r-- | routers/repo/issue.go | 10 | ||||
-rw-r--r-- | routers/repo/setting.go | 56 | ||||
-rw-r--r-- | routers/user/home.go | 24 | ||||
-rw-r--r-- | templates/.VERSION | 2 | ||||
-rw-r--r-- | templates/ng/base/footer.tmpl | 2 | ||||
-rw-r--r-- | templates/org/home.tmpl | 2 | ||||
-rw-r--r-- | templates/user/profile.tmpl | 2 |
22 files changed, 902 insertions, 1054 deletions
diff --git a/cmd/serve.go b/cmd/serve.go index 25f7dd9191..e8e5c186c7 100644 --- a/cmd/serve.go +++ b/cmd/serve.go @@ -8,7 +8,6 @@ import ( "fmt" "os" "os/exec" - "path" "path/filepath" "strings" "time" @@ -43,7 +42,7 @@ func setup(logPath string) { models.LoadModelsConfig() - if models.UseSQLite3 { + if setting.UseSQLite3 { workDir, _ := setting.WorkDir() os.Chdir(workDir) } @@ -67,33 +66,33 @@ func parseCmd(cmd string) (string, string) { } var ( - COMMANDS_READONLY = map[string]models.AccessType{ - "git-upload-pack": models.WRITABLE, - "git upload-pack": models.WRITABLE, - "git-upload-archive": models.WRITABLE, + COMMANDS_READONLY = map[string]models.AccessMode{ + "git-upload-pack": models.ACCESS_MODE_WRITE, + "git upload-pack": models.ACCESS_MODE_WRITE, + "git-upload-archive": models.ACCESS_MODE_WRITE, } - COMMANDS_WRITE = map[string]models.AccessType{ - "git-receive-pack": models.READABLE, - "git receive-pack": models.READABLE, + COMMANDS_WRITE = map[string]models.AccessMode{ + "git-receive-pack": models.ACCESS_MODE_READ, + "git receive-pack": models.ACCESS_MODE_READ, } ) -func In(b string, sl map[string]models.AccessType) bool { +func In(b string, sl map[string]models.AccessMode) bool { _, e := sl[b] return e } -func runServ(k *cli.Context) { - if k.IsSet("config") { - setting.CustomConf = k.String("config") +func runServ(c *cli.Context) { + if c.IsSet("config") { + setting.CustomConf = c.String("config") } setup("serv.log") - if len(k.Args()) < 1 { + if len(c.Args()) < 1 { log.GitLogger.Fatal(2, "Not enough arguments") } - keys := strings.Split(k.Args()[0], "-") + keys := strings.Split(c.Args()[0], "-") if len(keys) != 2 { println("Gogs: auth file format error") log.GitLogger.Fatal(2, "Invalid auth file format: %s", os.Args[2]) @@ -117,6 +116,7 @@ func runServ(k *cli.Context) { cmd := os.Getenv("SSH_ORIGINAL_COMMAND") if cmd == "" { println("Hi", user.Name, "! You've successfully authenticated, but Gogs does not provide shell access.") + println("If this is what you do not expect, please log in with password and setup Gogs under another user.") return } @@ -144,9 +144,19 @@ func runServ(k *cli.Context) { } // Access check. + repo, err := models.GetRepositoryByName(repoUser.Id, repoName) + if err != nil { + if err == models.ErrRepoNotExist { + println("Gogs: given repository does not exist") + log.GitLogger.Fatal(2, "Repository does not exist: %s/%s", repoUser.Name, repoName) + } + println("Gogs: internal error:", err.Error()) + log.GitLogger.Fatal(2, "Fail to get repository: %v", err) + } + switch { case isWrite: - has, err := models.HasAccess(user.Name, path.Join(repoUserName, repoName), models.WRITABLE) + has, err := models.HasAccess(user, repo, models.ACCESS_MODE_WRITE) if err != nil { println("Gogs: internal error:", err.Error()) log.GitLogger.Fatal(2, "Fail to check write access:", err) @@ -155,21 +165,11 @@ func runServ(k *cli.Context) { log.GitLogger.Fatal(2, "User %s has no right to write repository %s", user.Name, repoPath) } case isRead: - repo, err := models.GetRepositoryByName(repoUser.Id, repoName) - if err != nil { - if err == models.ErrRepoNotExist { - println("Gogs: given repository does not exist") - log.GitLogger.Fatal(2, "Repository does not exist: %s/%s", repoUser.Name, repoName) - } - println("Gogs: internal error:", err.Error()) - log.GitLogger.Fatal(2, "Fail to get repository: %v", err) - } - if !repo.IsPrivate { break } - has, err := models.HasAccess(user.Name, path.Join(repoUserName, repoName), models.READABLE) + has, err := models.HasAccess(user, repo, models.ACCESS_MODE_READ) if err != nil { println("Gogs: internal error:", err.Error()) log.GitLogger.Fatal(2, "Fail to check read access:", err) diff --git a/models/access.go b/models/access.go index 81aa43dc78..1e1c0114ed 100644 --- a/models/access.go +++ b/models/access.go @@ -4,77 +4,159 @@ package models -import ( - "strings" - "time" - - "github.com/go-xorm/xorm" -) - -type AccessType int +type AccessMode int const ( - READABLE AccessType = iota + 1 - WRITABLE + ACCESS_MODE_NONE AccessMode = iota + ACCESS_MODE_READ + ACCESS_MODE_WRITE + ACCESS_MODE_ADMIN + ACCESS_MODE_OWNER ) -// Access represents the accessibility of user to repository. +// Access represents the highest access level of a user to the 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 - UserName string `xorm:"UNIQUE(s)"` - RepoName string `xorm:"UNIQUE(s)"` // <user name>/<repo name> - Mode AccessType `xorm:"UNIQUE(s)"` - Created time.Time `xorm:"CREATED"` + ID int64 `xorm:"pk autoincr"` + UserID int64 `xorm:"UNIQUE(s)"` + RepoID int64 `xorm:"UNIQUE(s)"` + Mode AccessMode } -// AddAccess adds new access record. -func AddAccess(access *Access) error { - access.UserName = strings.ToLower(access.UserName) - access.RepoName = strings.ToLower(access.RepoName) - _, err := x.Insert(access) - return err +// Return the Access a user has to a repository. Will return NoneAccess if the +// user does not have access. User can be nil! +func AccessLevel(u *User, r *Repository) (AccessMode, error) { + mode := ACCESS_MODE_NONE + if !r.IsPrivate { + mode = ACCESS_MODE_READ + } + + if u != nil { + if u.Id == r.OwnerId { + return ACCESS_MODE_OWNER, nil + } + + a := &Access{UserID: u.Id, RepoID: r.Id} + if has, err := x.Get(a); !has || err != nil { + return mode, err + } + return a.Mode, nil + } + + return mode, nil } -// UpdateAccess updates access information. -func UpdateAccess(access *Access) error { - access.UserName = strings.ToLower(access.UserName) - access.RepoName = strings.ToLower(access.RepoName) - _, err := x.Id(access.Id).Update(access) - return err +// HasAccess returns true if someone has the request access level. User can be nil! +func HasAccess(u *User, r *Repository, testMode AccessMode) (bool, error) { + mode, err := AccessLevel(u, r) + return testMode <= mode, err } -// DeleteAccess deletes access record. -func DeleteAccess(access *Access) error { - _, err := x.Delete(access) - return err +// GetAccessibleRepositories finds all repositories where a user has access to, +// besides his own. +func (u *User) GetAccessibleRepositories() (map[*Repository]AccessMode, error) { + accesses := make([]*Access, 0, 10) + if err := x.Find(&accesses, &Access{UserID: u.Id}); err != nil { + return nil, err + } + + repos := make(map[*Repository]AccessMode, len(accesses)) + for _, access := range accesses { + repo, err := GetRepositoryById(access.RepoID) + if err != nil { + return nil, err + } + if err = repo.GetOwner(); err != nil { + return nil, err + } else if repo.OwnerId == u.Id { + continue + } + repos[repo] = access.Mode + } + + return repos, nil } -// UpdateAccess updates access information with session for rolling back. -func UpdateAccessWithSession(sess *xorm.Session, access *Access) error { - if _, err := sess.Id(access.Id).Update(access); err != nil { - sess.Rollback() - return err +func maxAccessMode(modes ...AccessMode) AccessMode { + max := ACCESS_MODE_NONE + for _, mode := range modes { + if mode > max { + max = mode + } } + return max +} + +func (repo *Repository) recalculateTeamAccesses(e Engine, mode AccessMode) error { + return nil } -// HasAccess returns true if someone can read or write to given repository. -// The repoName should be in format <username>/<reponame>. -func HasAccess(uname, repoName string, mode AccessType) (bool, error) { - if len(repoName) == 0 { - return false, nil +func (repo *Repository) recalculateAccesses(e Engine) error { + accessMap := make(map[int64]AccessMode, 20) + + // Give all collaborators write access + collaborators, err := repo.getCollaborators(e) + if err != nil { + return err } - access := &Access{ - UserName: strings.ToLower(uname), - RepoName: strings.ToLower(repoName), + for _, c := range collaborators { + accessMap[c.Id] = ACCESS_MODE_WRITE } - has, err := x.Get(access) - if err != nil { - return false, err - } else if !has { - return false, nil - } else if mode > access.Mode { - return false, nil + + if err := repo.getOwner(e); err != nil { + return err + } + if repo.Owner.IsOrganization() { + if err = repo.Owner.getTeams(e); err != nil { + return err + } + + for _, team := range repo.Owner.Teams { + if !(team.IsOwnerTeam() || team.HasRepository(repo)) { + continue + } else if team.IsOwnerTeam() { + team.Authorize = ACCESS_MODE_OWNER + } + + if err = team.getMembers(e); err != nil { + return err + } + for _, u := range team.Members { + accessMap[u.Id] = maxAccessMode(accessMap[u.Id], team.Authorize) + } + } + } + + minMode := ACCESS_MODE_READ + if !repo.IsPrivate { + minMode = ACCESS_MODE_WRITE + } + + newAccesses := make([]Access, 0, len(accessMap)) + for userID, mode := range accessMap { + if mode < minMode { + continue + } + newAccesses = append(newAccesses, Access{ + UserID: userID, + RepoID: repo.Id, + Mode: mode, + }) + } + + // Delete old accesses and insert new ones for repository. + if _, err = e.Delete(&Access{RepoID: repo.Id}); err != nil { + return err + } else if _, err = e.Insert(newAccesses); err != nil { + return err } - return true, nil + + return nil +} + +// RecalculateAccesses recalculates all accesses for repository. +func (r *Repository) RecalculateAccesses() error { + return r.recalculateAccesses(x) } diff --git a/models/action.go b/models/action.go index 5cba2f515a..9ba661f1e2 100644 --- a/models/action.go +++ b/models/action.go @@ -412,21 +412,29 @@ func CommitRepoAction(userId, repoUserId int64, userName, actEmail string, return nil } -// NewRepoAction adds new action for creating repository. -func NewRepoAction(u *User, repo *Repository) (err error) { - if err = NotifyWatchers(&Action{ActUserId: u.Id, ActUserName: u.Name, ActEmail: u.Email, - OpType: CREATE_REPO, RepoId: repo.Id, RepoUserName: repo.Owner.Name, RepoName: repo.Name, - IsPrivate: repo.IsPrivate}); err != nil { - log.Error(4, "NotifyWatchers: %d/%s", u.Id, repo.Name) - return err +func newRepoAction(e Engine, u *User, repo *Repository) (err error) { + if err = notifyWatchers(e, &Action{ + ActUserId: u.Id, + ActUserName: u.Name, + ActEmail: u.Email, + OpType: CREATE_REPO, + RepoId: repo.Id, + RepoUserName: repo.Owner.Name, + RepoName: repo.Name, + IsPrivate: repo.IsPrivate}); err != nil { + return fmt.Errorf("notify watchers '%d/%s'", u.Id, repo.Id) } log.Trace("action.NewRepoAction: %s/%s", u.Name, repo.Name) return err } -// TransferRepoAction adds new action for transferring repository. -func TransferRepoAction(u, newUser *User, repo *Repository) (err error) { +// NewRepoAction adds new action for creating repository. +func NewRepoAction(u *User, repo *Repository) (err error) { + return newRepoAction(x, u, repo) +} + +func transferRepoAction(e Engine, u, newUser *User, repo *Repository) (err error) { action := &Action{ ActUserId: u.Id, ActUserName: u.Name, @@ -438,20 +446,24 @@ func TransferRepoAction(u, newUser *User, repo *Repository) (err error) { IsPrivate: repo.IsPrivate, Content: path.Join(repo.Owner.LowerName, repo.LowerName), } - if err = NotifyWatchers(action); err != nil { - log.Error(4, "NotifyWatchers: %d/%s", u.Id, repo.Name) - return err + if err = notifyWatchers(e, action); err != nil { + return fmt.Errorf("notify watchers '%d/%s'", u.Id, repo.Id) } // Remove watch for organization. if repo.Owner.IsOrganization() { - if err = WatchRepo(repo.Owner.Id, repo.Id, false); err != nil { - log.Error(4, "WatchRepo", err) + if err = watchRepo(e, repo.Owner.Id, repo.Id, false); err != nil { + return fmt.Errorf("watch repository: %v", err) } } log.Trace("action.TransferRepoAction: %s/%s", u.Name, repo.Name) - return err + return nil +} + +// TransferRepoAction adds new action for transferring repository. +func TransferRepoAction(u, newUser *User, repo *Repository) (err error) { + return transferRepoAction(x, u, newUser, repo) } // GetFeeds returns action list of given user in given context. diff --git a/models/issue.go b/models/issue.go index 226ca3ca57..2b80e57608 100644 --- a/models/issue.go +++ b/models/issue.go @@ -282,30 +282,33 @@ type IssueUser struct { } // NewIssueUserPairs adds new issue-user pairs for new issue of repository. -func NewIssueUserPairs(rid, iid, oid, pid, aid int64, repoName string) (err error) { - iu := &IssueUser{IssueId: iid, RepoId: rid} - - us, err := GetCollaborators(repoName) +func NewIssueUserPairs(repo *Repository, issueID, orgID, posterID, assigneeID int64) (err error) { + users, err := repo.GetCollaborators() if err != nil { return err } + iu := &IssueUser{ + IssueId: issueID, + RepoId: repo.Id, + } + isNeedAddPoster := true - for _, u := range us { + for _, u := range users { iu.Uid = u.Id - iu.IsPoster = iu.Uid == pid + iu.IsPoster = iu.Uid == posterID if isNeedAddPoster && iu.IsPoster { isNeedAddPoster = false } - iu.IsAssigned = iu.Uid == aid + iu.IsAssigned = iu.Uid == assigneeID if _, err = x.Insert(iu); err != nil { return err } } if isNeedAddPoster { - iu.Uid = pid + iu.Uid = posterID iu.IsPoster = true - iu.IsAssigned = iu.Uid == aid + iu.IsAssigned = iu.Uid == assigneeID if _, err = x.Insert(iu); err != nil { return err } diff --git a/models/migrations/migrations.go b/models/migrations/migrations.go index 3586e5d0b6..e69b0a1f5e 100644 --- a/models/migrations/migrations.go +++ b/models/migrations/migrations.go @@ -1,12 +1,44 @@ +// 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 ( - "errors" + "fmt" + "strings" + "time" + "github.com/Unknwon/com" "github.com/go-xorm/xorm" + + "github.com/gogits/gogs/modules/log" + "github.com/gogits/gogs/modules/setting" ) -type migration func(*xorm.Engine) error +const _MIN_DB_VER = 0 + +type Migration interface { + Description() string + Migrate(*xorm.Engine) error +} + +type migration struct { + description string + migrate func(*xorm.Engine) error +} + +func NewMigration(desc string, fn func(*xorm.Engine) error) Migration { + return &migration{desc, fn} +} + +func (m *migration) Description() string { + return m.description +} + +func (m *migration) Migrate(x *xorm.Engine) error { + return m.migrate(x) +} // The version table. Should have only one row with id==1 type Version struct { @@ -15,30 +47,53 @@ type Version struct { } // This is a sequence of migrations. Add new migrations to the bottom of the list. -// If you want to "retire" a migration, replace it with "expiredMigration" -var migrations = []migration{} +// If you want to "retire" a migration, remove it from the top of the list and +// update _MIN_VER_DB accordingly +var migrations = []Migration{ + NewMigration("generate collaboration from access", accessToCollaboration), // V0 -> V1 + NewMigration("refactor access table to use id's", accessRefactor), // V1 -> V2 +} // Migrate database to current version func Migrate(x *xorm.Engine) error { if err := x.Sync(new(Version)); err != nil { - return err + return fmt.Errorf("sync: %v", err) } currentVersion := &Version{Id: 1} has, err := x.Get(currentVersion) if err != nil { - return err + return fmt.Errorf("get: %v", err) } else if !has { - if _, err = x.InsertOne(currentVersion); err != nil { + // If the user table does not exist it is a fresh installation and we + // can skip all migrations. + needsMigration, err := x.IsTableExist("user") + if err != nil { return err } + if needsMigration { + isEmpty, err := x.IsTableEmpty("user") + if err != nil { + return err + } + // If the user table is empty it is a fresh installation and we can + // skip all migrations. + needsMigration = !isEmpty + } + if !needsMigration { + currentVersion.Version = int64(_MIN_DB_VER + len(migrations)) + } + + if _, err = x.InsertOne(currentVersion); err != nil { + return fmt.Errorf("insert: %v", err) + } } v := currentVersion.Version - - for i, migration := range migrations[v:] { - if err = migration(x); err != nil { - return err + for i, m := range migrations[v-_MIN_DB_VER:] { + log.Info("Migration: %s", m.Description()) + if err = m.Migrate(x); err != nil { + return fmt.Errorf("do migrate: %v", err) } currentVersion.Version = v + int64(i) + 1 if _, err = x.Id(1).Update(currentVersion); err != nil { @@ -48,6 +103,199 @@ func Migrate(x *xorm.Engine) error { return nil } -func expiredMigration(x *xorm.Engine) error { - return errors.New("You are migrating from a too old gogs version") +func sessionRelease(sess *xorm.Session) { + if !sess.IsCommitedOrRollbacked { + sess.Rollback() + } + sess.Close() +} + +func accessToCollaboration(x *xorm.Engine) (err error) { + type Collaboration struct { + ID int64 `xorm:"pk autoincr"` + RepoID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"` + UserID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"` + Created time.Time + } + + if err = x.Sync(new(Collaboration)); err != nil { + return fmt.Errorf("sync: %v", err) + } + + results, err := x.Query("SELECT u.id AS `uid`, a.repo_name AS `repo`, a.mode AS `mode`, a.created as `created` FROM `access` a JOIN `user` u ON a.user_name=u.lower_name") + if err != nil { + return err + } + + sess := x.NewSession() + defer sessionRelease(sess) + if err = sess.Begin(); err != nil { + return err + } + + offset := strings.Split(time.Now().String(), " ")[2] + for _, result := range results { + mode := com.StrTo(result["mode"]).MustInt64() + // Collaborators must have write access. + if mode < 2 { + continue + } + + userID := com.StrTo(result["uid"]).MustInt64() + repoRefName := string(result["repo"]) + + var created time.Time + switch { + case setting.UseSQLite3: + created, _ = time.Parse(time.RFC3339, string(result["created"])) + case setting.UseMySQL: + created, _ = time.Parse("2006-01-02 15:04:05-0700", string(result["created"])+offset) + case setting.UsePostgreSQL: + created, _ = time.Parse("2006-01-02T15:04:05Z-0700", string(result["created"])+offset) + } + + // find owner of repository + parts := strings.SplitN(repoRefName, "/", 2) + ownerName := parts[0] + repoName := parts[1] + + results, err := sess.Query("SELECT u.id as `uid`, ou.uid as `memberid` FROM `user` u LEFT JOIN org_user ou ON ou.org_id=u.id WHERE u.lower_name=?", ownerName) + if err != nil { + return err + } + if len(results) < 1 { + continue + } + + ownerID := com.StrTo(results[0]["uid"]).MustInt64() + if ownerID == userID { + continue + } + + // test if user is member of owning organization + isMember := false + for _, member := range results { + memberID := com.StrTo(member["memberid"]).MustInt64() + // We can skip all cases that a user is member of the owning organization + if memberID == userID { + isMember = true + } + } + if isMember { + continue + } + + results, err = sess.Query("SELECT id FROM `repository` WHERE owner_id=? AND lower_name=?", ownerID, repoName) + if err != nil { + return err + } else if len(results) < 1 { + continue + } + + collaboration := &Collaboration{ + UserID: userID, + RepoID: com.StrTo(results[0]["id"]).MustInt64(), + } + has, err := sess.Get(collaboration) + if err != nil { + return err + } else if has { + continue + } + + collaboration.Created = created + if _, err = sess.InsertOne(collaboration); err != nil { + return err + } + } + + return sess.Commit() +} + +func accessRefactor(x *xorm.Engine) (err error) { + type ( + AccessMode int + Access struct { + ID int64 `xorm:"pk autoincr"` + UserName string + RepoName string + UserID int64 `xorm:"UNIQUE(s)"` + RepoID int64 `xorm:"UNIQUE(s)"` + Mode AccessMode + } + ) + + var rawSQL string + switch { + case setting.UseSQLite3, setting.UsePostgreSQL: + rawSQL = "DROP INDEX IF EXISTS `UQE_access_S`" + case setting.UseMySQL: + rawSQL = "DROP INDEX `UQE_access_S` ON `access`" + } + if _, err = x.Exec(rawSQL); err != nil && + !strings.Contains(err.Error(), "check that column/key exists") { + return fmt.Errorf("drop index: %v", err) + } + + sess := x.NewSession() + defer sessionRelease(sess) + if err = sess.Begin(); err != nil { + return err + } + + if err = sess.Sync2(new(Access)); err != nil { + return fmt.Errorf("sync: %v", err) + } + + accesses := make([]*Access, 0, 50) + if err = sess.Iterate(new(Access), func(idx int, bean interface{}) error { + a := bean.(*Access) + + // Update username to user ID. + users, err := sess.Query("SELECT `id` FROM `user` WHERE lower_name=?", a.UserName) + if err != nil { + return fmt.Errorf("query user: %v", err) + } else if len(users) < 1 { + return nil + } + a.UserID = com.StrTo(users[0]["id"]).MustInt64() + + // Update repository name(username/reponame) to repository ID. + names := strings.Split(a.RepoName, "/") + ownerName := names[0] + repoName := names[1] + + // Check if user is the owner of the repository. + ownerID := a.UserID + if ownerName != a.UserName { + users, err := sess.Query("SELECT `id` FROM `user` WHERE lower_name=?", ownerName) + if err != nil { + return fmt.Errorf("query owner: %v", err) + } else if len(users) < 1 { + return nil + } + ownerID = com.StrTo(users[0]["id"]).MustInt64() + } + + repos, err := sess.Query("SELECT `id` FROM `repository` WHERE owner_id=? AND lower_name=?", ownerID, repoName) + if err != nil { + return fmt.Errorf("query repository: %v", err) + } else if len(repos) < 1 { + return nil + } + a.RepoID = com.StrTo(repos[0]["id"]).MustInt64() + + accesses = append(accesses, a) + return nil + }); err != nil { + return fmt.Errorf("iterate: %v", err) + } + + for i := range accesses { + if _, err = sess.Id(accesses[i].ID).Update(accesses[i]); err != nil { + return fmt.Errorf("update: %v", err) + } + } + + return sess.Commit() } diff --git a/models/models.go b/models/models.go index 486aceac22..b0c3b8978f 100644 --- a/models/models.go +++ b/models/models.go @@ -12,6 +12,7 @@ import ( "strings" _ "github.com/go-sql-driver/mysql" + "github.com/go-xorm/core" "github.com/go-xorm/xorm" _ "github.com/lib/pq" @@ -23,12 +24,22 @@ import ( type Engine interface { Delete(interface{}) (int64, error) Exec(string, ...interface{}) (sql.Result, error) + Find(interface{}, ...interface{}) error Get(interface{}) (bool, error) Insert(...interface{}) (int64, error) + InsertOne(interface{}) (int64, error) Id(interface{}) *xorm.Session + Sql(string, ...interface{}) *xorm.Session Where(string, ...interface{}) *xorm.Session } +func sessionRelease(sess *xorm.Session) { + if !sess.IsCommitedOrRollbacked { + sess.Rollback() + } + sess.Close() +} + var ( x *xorm.Engine tables []interface{} @@ -39,13 +50,13 @@ var ( } EnableSQLite3 bool - UseSQLite3 bool ) func init() { tables = append(tables, - new(User), new(PublicKey), new(Follow), new(Oauth2), new(AccessToken), - new(Repository), new(Watch), new(Star), new(Action), new(Access), + new(User), new(PublicKey), new(Oauth2), new(AccessToken), + new(Repository), new(Collaboration), new(Access), + new(Watch), new(Star), new(Follow), new(Action), new(Issue), new(Comment), new(Attachment), new(IssueUser), new(Label), new(Milestone), new(Mirror), new(Release), new(LoginSource), new(Webhook), new(UpdateTask), new(HookTask), new(Team), new(OrgUser), new(TeamUser), @@ -55,8 +66,13 @@ func init() { func LoadModelsConfig() { sec := setting.Cfg.Section("database") DbCfg.Type = sec.Key("DB_TYPE").String() - if DbCfg.Type == "sqlite3" { - UseSQLite3 = true + switch DbCfg.Type { + case "sqlite3": + setting.UseSQLite3 = true + case "mysql": + setting.UseMySQL = true + case "postgres": + setting.UsePostgreSQL = true } DbCfg.Host = sec.Key("HOST").String() DbCfg.Name = sec.Key("NAME").String() @@ -103,6 +119,7 @@ func NewTestEngine(x *xorm.Engine) (err error) { return fmt.Errorf("connect to database: %v", err) } + x.SetMapper(core.GonicMapper{}) return x.Sync(tables...) } @@ -112,6 +129,8 @@ func SetEngine() (err error) { return fmt.Errorf("connect to database: %v", err) } + x.SetMapper(core.GonicMapper{}) + // WARNING: for serv command, MUST remove the output to os.stdout, // so use log file to instead print to stdout. logPath := path.Join(setting.LogRootPath, "xorm.log") @@ -136,13 +155,14 @@ func NewEngine() (err error) { return err } - // if err = migrations.Migrate(x); err != nil { - // return err - // } + if err = migrations.Migrate(x); err != nil { + return fmt.Errorf("migrate: %v", err) + } if err = x.StoreEngine("InnoDB").Sync2(tables...); err != nil { return fmt.Errorf("sync database struct error: %v\n", err) } + return nil } diff --git a/models/org.go b/models/org.go index b2f9c903a4..36cf5f7d1a 100644 --- a/models/org.go +++ b/models/org.go @@ -6,9 +6,7 @@ package models import ( "errors" - "fmt" "os" - "path" "strings" "github.com/Unknwon/com" @@ -34,19 +32,31 @@ func (org *User) IsOrgMember(uid int64) bool { return IsOrganizationMember(org.Id, uid) } +func (org *User) getTeam(e Engine, name string) (*Team, error) { + return getTeam(e, org.Id, name) +} + // GetTeam returns named team of organization. func (org *User) GetTeam(name string) (*Team, error) { - return GetTeam(org.Id, name) + return org.getTeam(x, name) +} + +func (org *User) getOwnerTeam(e Engine) (*Team, error) { + return org.getTeam(e, OWNER_TEAM) } // GetOwnerTeam returns owner team of organization. func (org *User) GetOwnerTeam() (*Team, error) { - return org.GetTeam(OWNER_TEAM) + return org.getOwnerTeam(x) +} + +func (org *User) getTeams(e Engine) error { + return e.Where("org_id=?", org.Id).Find(&org.Teams) } // GetTeams returns all teams that belong to organization. func (org *User) GetTeams() error { - return x.Where("org_id=?", org.Id).Find(&org.Teams) + return org.getTeams(x) } // GetMembers returns all members of organization. @@ -136,7 +146,7 @@ func CreateOrganization(org, owner *User) (*User, error) { OrgId: org.Id, LowerName: strings.ToLower(OWNER_TEAM), Name: OWNER_TEAM, - Authorize: ORG_ADMIN, + Authorize: ACCESS_MODE_OWNER, NumMembers: 1, } if _, err = sess.Insert(t); err != nil { @@ -371,10 +381,10 @@ func RemoveOrgUser(orgId, uid int64) error { return err } access := &Access{ - UserName: u.LowerName, + UserID: u.Id, } for _, repo := range org.Repos { - access.RepoName = path.Join(org.LowerName, repo.LowerName) + access.RepoID = repo.Id if _, err = sess.Delete(access); err != nil { sess.Rollback() return err @@ -405,21 +415,6 @@ func RemoveOrgUser(orgId, uid int64) error { // |____| \___ >____ /__|_| / // \/ \/ \/ -type AuthorizeType int - -const ( - ORG_READABLE AuthorizeType = iota + 1 - ORG_WRITABLE - ORG_ADMIN -) - -func AuthorizeToAccessType(auth AuthorizeType) AccessType { - if auth == ORG_READABLE { - return READABLE - } - return WRITABLE -} - const OWNER_TEAM = "Owners" // Team represents a organization team. @@ -429,7 +424,7 @@ type Team struct { LowerName string Name string Description string - Authorize AuthorizeType + Authorize AccessMode RepoIds string `xorm:"TEXT"` Repos []*Repository `xorm:"-"` Members []*User `xorm:"-"` @@ -447,8 +442,7 @@ func (t *Team) IsMember(uid int64) bool { return IsTeamMember(t.OrgId, t.Id, uid) } -// GetRepositories returns all repositories in team of organization. -func (t *Team) GetRepositories() error { +func (t *Team) getRepositories(e Engine) error { idStrs := strings.Split(t.RepoIds, "|") t.Repos = make([]*Repository, 0, len(idStrs)) for _, str := range idStrs { @@ -459,7 +453,7 @@ func (t *Team) GetRepositories() error { if id == 0 { continue } - repo, err := GetRepositoryById(id) + repo, err := getRepositoryById(e, id) if err != nil { return err } @@ -468,10 +462,19 @@ func (t *Team) GetRepositories() error { 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) { - t.Members, err = GetTeamMembers(t.OrgId, t.Id) - return err + return t.getMembers(x) } // AddMember adds new member to team of organization. @@ -484,25 +487,6 @@ func (t *Team) RemoveMember(uid int64) error { return RemoveTeamMember(t.OrgId, t.Id, uid) } -// addAccessWithAuthorize inserts or updates access with given mode. -func addAccessWithAuthorize(e Engine, access *Access, mode AccessType) error { - has, err := e.Get(access) - if err != nil { - return fmt.Errorf("fail to get access: %v", err) - } - access.Mode = mode - if has { - if _, err = e.Id(access.Id).Update(access); err != nil { - return fmt.Errorf("fail to update access: %v", err) - } - } else { - if _, err = e.Insert(access); err != nil { - return fmt.Errorf("fail to insert access: %v", err) - } - } - return nil -} - // AddRepository adds new repository to team of organization. func (t *Team) AddRepository(repo *Repository) (err error) { idStr := "$" + com.ToStr(repo.Id) + "|" @@ -519,7 +503,7 @@ func (t *Team) AddRepository(repo *Repository) (err error) { } sess := x.NewSession() - defer sess.Close() + defer sessionRelease(sess) if err = sess.Begin(); err != nil { return err } @@ -527,38 +511,26 @@ func (t *Team) AddRepository(repo *Repository) (err error) { t.NumRepos++ t.RepoIds += idStr if _, err = sess.Id(t.Id).AllCols().Update(t); err != nil { - sess.Rollback() return err } - // Give access to team members. - mode := AuthorizeToAccessType(t.Authorize) + if err = repo.recalculateAccesses(sess); err != nil { + return err + } for _, u := range t.Members { - auth, err := getHighestAuthorize(sess, t.OrgId, u.Id, repo.Id, t.Id) - if err != nil { - sess.Rollback() - return err - } - - access := &Access{ - UserName: u.LowerName, - RepoName: path.Join(repo.Owner.LowerName, repo.LowerName), - } - if auth < t.Authorize { - if err = addAccessWithAuthorize(sess, access, mode); err != nil { - sess.Rollback() - return err - } - } if err = watchRepo(sess, u.Id, repo.Id, true); err != nil { - sess.Rollback() return err } } return sess.Commit() } +func (t *Team) HasRepository(repo *Repository) bool { + idStr := "$" + com.ToStr(repo.Id) + "|" + return strings.Contains(t.RepoIds, idStr) +} + // RemoveRepository removes repository from team of organization. func (t *Team) RemoveRepository(repoId int64) error { idStr := "$" + com.ToStr(repoId) + "|" @@ -578,7 +550,7 @@ func (t *Team) RemoveRepository(repoId int64) error { } sess := x.NewSession() - defer sess.Close() + defer sessionRelease(sess) if err = sess.Begin(); err != nil { return err } @@ -586,36 +558,17 @@ func (t *Team) RemoveRepository(repoId int64) error { t.NumRepos-- t.RepoIds = strings.Replace(t.RepoIds, idStr, "", 1) if _, err = sess.Id(t.Id).AllCols().Update(t); err != nil { - sess.Rollback() return err } - // Remove access to team members. + if err = repo.recalculateAccesses(sess); err != nil { + return err + } + for _, u := range t.Members { - auth, err := getHighestAuthorize(sess, t.OrgId, u.Id, repo.Id, t.Id) - if err != nil { - sess.Rollback() + if err = watchRepo(sess, u.Id, repo.Id, false); err != nil { return err } - - access := &Access{ - UserName: u.LowerName, - RepoName: path.Join(repo.Owner.LowerName, repo.LowerName), - } - if auth == 0 { - if _, err = sess.Delete(access); err != nil { - sess.Rollback() - return fmt.Errorf("fail to delete access: %v", err) - } else if err = watchRepo(sess, u.Id, repo.Id, false); err != nil { - sess.Rollback() - return err - } - } else if auth < t.Authorize { - if err = addAccessWithAuthorize(sess, access, AuthorizeToAccessType(auth)); err != nil { - sess.Rollback() - return err - } - } } return sess.Commit() @@ -662,13 +615,12 @@ func NewTeam(t *Team) error { return sess.Commit() } -// GetTeam returns team by given team name and organization. -func GetTeam(orgId int64, name string) (*Team, error) { +func getTeam(e Engine, orgId int64, name string) (*Team, error) { t := &Team{ OrgId: orgId, LowerName: strings.ToLower(name), } - has, err := x.Get(t) + has, err := e.Get(t) if err != nil { return nil, err } else if !has { @@ -677,6 +629,11 @@ func GetTeam(orgId int64, name string) (*Team, error) { return t, nil } +// GetTeam returns team by given team name and organization. +func GetTeam(orgId int64, name string) (*Team, error) { + return getTeam(x, orgId, name) +} + func getTeamById(e Engine, teamId int64) (*Team, error) { t := new(Team) has, err := e.Id(teamId).Get(t) @@ -693,34 +650,6 @@ func GetTeamById(teamId int64) (*Team, error) { return getTeamById(x, teamId) } -func getHighestAuthorize(e Engine, orgId, uid, repoId, teamId int64) (AuthorizeType, error) { - ts, err := getUserTeams(e, orgId, uid) - if err != nil { - return 0, err - } - - var auth AuthorizeType = 0 - for _, t := range ts { - // Not current team and has given repository. - if t.Id != teamId && strings.Contains(t.RepoIds, "$"+com.ToStr(repoId)+"|") { - // Fast return. - if t.Authorize == ORG_WRITABLE { - return ORG_WRITABLE, nil - } - if t.Authorize > auth { - auth = t.Authorize - } - } - } - - return auth, nil -} - -// GetHighestAuthorize returns highest repository authorize level for given user and team. -func GetHighestAuthorize(orgId, uid, repoId, teamId int64) (AuthorizeType, error) { - return getHighestAuthorize(x, orgId, uid, repoId, teamId) -} - // UpdateTeam updates information of team. func UpdateTeam(t *Team, authChanged bool) (err error) { if !IsLegalName(t.Name) { @@ -732,58 +661,26 @@ func UpdateTeam(t *Team, authChanged bool) (err error) { } sess := x.NewSession() - defer sess.Close() + defer sessionRelease(sess) if err = sess.Begin(); err != nil { return err } // Update access for team members if needed. - if authChanged && !t.IsOwnerTeam() { - if err = t.GetRepositories(); err != nil { - return err - } else if err = t.GetMembers(); err != nil { + if authChanged { + if err = t.getRepositories(sess); err != nil { return err } - // Get organization. - org, err := GetUserById(t.OrgId) - if err != nil { - return err - } - - // Update access. - mode := AuthorizeToAccessType(t.Authorize) - for _, repo := range t.Repos { - for _, u := range t.Members { - // ORG_WRITABLE is the highest authorize level for now. - // Skip checking others if current team has this level. - if t.Authorize < ORG_WRITABLE { - auth, err := GetHighestAuthorize(t.OrgId, u.Id, repo.Id, t.Id) - if err != nil { - sess.Rollback() - return err - } - if auth >= t.Authorize { - continue // Other team has higher or same authorize level. - } - } - - access := &Access{ - UserName: u.LowerName, - RepoName: path.Join(org.LowerName, repo.LowerName), - } - if err = addAccessWithAuthorize(sess, access, mode); err != nil { - sess.Rollback() - return err - } + if err = repo.recalculateAccesses(sess); err != nil { + return err } } } t.LowerName = strings.ToLower(t.Name) if _, err = sess.Id(t.Id).AllCols().Update(t); err != nil { - sess.Rollback() return err } return sess.Commit() @@ -805,53 +702,29 @@ func DeleteTeam(t *Team) error { } sess := x.NewSession() - defer sess.Close() + defer sessionRelease(sess) if err = sess.Begin(); err != nil { return err } // Delete all accesses. for _, repo := range t.Repos { - for _, u := range t.Members { - auth, err := GetHighestAuthorize(t.OrgId, u.Id, repo.Id, t.Id) - if err != nil { - sess.Rollback() - return err - } - - access := &Access{ - UserName: u.LowerName, - RepoName: path.Join(org.LowerName, repo.LowerName), - } - if auth == 0 { - if _, err = sess.Delete(access); err != nil { - sess.Rollback() - return fmt.Errorf("fail to delete access: %v", err) - } - } else if auth < t.Authorize { - // Downgrade authorize level. - if err = addAccessWithAuthorize(sess, access, AuthorizeToAccessType(auth)); err != nil { - sess.Rollback() - return err - } - } + if err = repo.recalculateAccesses(sess); 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 { - sess.Rollback() return err } // Delete team. if _, err = sess.Id(t.Id).Delete(new(Team)); err != nil { - sess.Rollback() 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 { - sess.Rollback() return err } @@ -883,13 +756,17 @@ func IsTeamMember(orgId, teamId, uid int64) bool { return isTeamMember(x, orgId, teamId, uid) } -// GetTeamMembers returns all members in given team of organization. -func GetTeamMembers(orgId, teamId int64) ([]*User, error) { +func getTeamMembers(e Engine, teamID int64) ([]*User, error) { us := make([]*User, 0, 10) - err := x.Sql("SELECT * FROM `user` JOIN `team_user` ON `team_user`.`team_id` = ? AND `team_user`.`uid` = `user`.`id`", teamId).Find(&us) + err := e.Sql("SELECT * FROM `user` JOIN `team_user` ON `team_user`.`team_id` = ? AND `team_user`.`uid` = `user`.`id`", teamID).Find(&us) return us, err } +// GetTeamMembers returns all members in given team of organization. +func GetTeamMembers(teamID int64) ([]*User, error) { + return getTeamMembers(x, teamID) +} + func getUserTeams(e Engine, orgId, uid int64) ([]*Team, error) { tus := make([]*TeamUser, 0, 5) if err := e.Where("uid=?", uid).And("org_id=?", orgId).Find(&tus); err != nil { @@ -936,20 +813,8 @@ func AddTeamMember(orgId, teamId, uid int64) error { return err } - // Get organization. - org, err := GetUserById(orgId) - if err != nil { - return err - } - - // Get user. - u, err := GetUserById(uid) - if err != nil { - return err - } - sess := x.NewSession() - defer sess.Close() + defer sessionRelease(sess) if err = sess.Begin(); err != nil { return err } @@ -961,39 +826,21 @@ func AddTeamMember(orgId, teamId, uid int64) error { } if _, err = sess.Insert(tu); err != nil { - sess.Rollback() return err } else if _, err = sess.Id(t.Id).Update(t); err != nil { - sess.Rollback() return err } // Give access to team repositories. - mode := AuthorizeToAccessType(t.Authorize) for _, repo := range t.Repos { - auth, err := getHighestAuthorize(sess, t.OrgId, u.Id, repo.Id, teamId) - if err != nil { - sess.Rollback() + if err = repo.recalculateAccesses(sess); err != nil { return err } - - access := &Access{ - UserName: u.LowerName, - RepoName: path.Join(org.LowerName, repo.LowerName), - } - if auth < t.Authorize { - if err = addAccessWithAuthorize(sess, access, mode); err != nil { - sess.Rollback() - return err - } - } } // We make sure it exists before. ou := new(OrgUser) - _, err = sess.Where("uid=?", uid).And("org_id=?", orgId).Get(ou) - if err != nil { - sess.Rollback() + if _, err = sess.Where("uid=?", uid).And("org_id=?", orgId).Get(ou); err != nil { return err } ou.NumTeams++ @@ -1001,7 +848,6 @@ func AddTeamMember(orgId, teamId, uid int64) error { ou.IsOwner = true } if _, err = sess.Id(ou.Id).AllCols().Update(ou); err != nil { - sess.Rollback() return err } @@ -1026,18 +872,12 @@ func removeTeamMember(e Engine, orgId, teamId, uid int64) error { t.NumMembers-- - if err = t.GetRepositories(); err != nil { + if err = t.getRepositories(e); err != nil { return err } // Get organization. - org, err := GetUserById(orgId) - if err != nil { - return err - } - - // Get user. - u, err := GetUserById(uid) + org, err := getUserById(e, orgId) if err != nil { return err } @@ -1056,28 +896,9 @@ func removeTeamMember(e Engine, orgId, teamId, uid int64) error { // Delete access to team repositories. for _, repo := range t.Repos { - auth, err := getHighestAuthorize(e, t.OrgId, u.Id, repo.Id, teamId) - if err != nil { + if err = repo.recalculateAccesses(e); err != nil { return err } - - access := &Access{ - UserName: u.LowerName, - RepoName: path.Join(org.LowerName, repo.LowerName), - } - // Delete access if this is the last team user belongs to. - if auth == 0 { - if _, err = e.Delete(access); err != nil { - return fmt.Errorf("fail to delete access: %v", err) - } else if err = watchRepo(e, u.Id, repo.Id, false); err != nil { - return err - } - } else if auth < t.Authorize { - // Downgrade authorize level. - if err = addAccessWithAuthorize(e, access, AuthorizeToAccessType(auth)); err != nil { - return err - } - } } // This must exist. diff --git a/models/repo.go b/models/repo.go index 179120a311..90cfdba854 100644 --- a/models/repo.go +++ b/models/repo.go @@ -166,13 +166,17 @@ type Repository struct { Updated time.Time `xorm:"UPDATED"` } -func (repo *Repository) GetOwner() (err error) { +func (repo *Repository) getOwner(e Engine) (err error) { if repo.Owner == nil { - repo.Owner, err = GetUserById(repo.OwnerId) + repo.Owner, err = getUserById(e, repo.OwnerId) } return err } +func (repo *Repository) GetOwner() (err error) { + return repo.getOwner(x) +} + func (repo *Repository) GetMirror() (err error) { repo.Mirror, err = GetMirror(repo.Id) return err @@ -201,16 +205,13 @@ func (repo *Repository) RepoLink() (string, error) { return setting.AppSubUrl + "/" + repo.Owner.Name + "/" + repo.Name, nil } -func (repo *Repository) IsOwnedBy(u *User) bool { - return repo.OwnerId == u.Id +func (repo *Repository) HasAccess(u *User) bool { + has, _ := HasAccess(u, repo, ACCESS_MODE_READ) + return has } -func (repo *Repository) HasAccess(uname string) bool { - if err := repo.GetOwner(); err != nil { - return false - } - has, _ := HasAccess(uname, path.Join(repo.Owner.Name, repo.Name), READABLE) - return has +func (repo *Repository) IsOwnedBy(u *User) bool { + return repo.OwnerId == u.Id } // DescriptionHtml does special handles to description and return HTML string. @@ -410,7 +411,7 @@ func createUpdateHook(repoPath string) error { } // InitRepository initializes README and .gitignore if needed. -func initRepository(f string, u *User, repo *Repository, initReadme bool, repoLang, license string) error { +func initRepository(e Engine, f string, u *User, repo *Repository, initReadme bool, repoLang, license string) error { repoPath := RepoPath(u.Name, repo.Name) // Create bare new repository. @@ -500,12 +501,12 @@ func initRepository(f string, u *User, repo *Repository, initReadme bool, repoLa if len(fileName) == 0 { // Re-fetch the repository from database before updating it (else it would // override changes that were done earlier with sql) - if repo, err = GetRepositoryById(repo.Id); err != nil { + if repo, err = getRepositoryById(e, repo.Id); err != nil { return err } repo.IsBare = true repo.DefaultBranch = "master" - return UpdateRepository(repo) + return updateRepository(e, repo) } // Apply changes and commit. @@ -525,12 +526,6 @@ func CreateRepository(u *User, name, desc, lang, license string, private, mirror return nil, ErrRepoAlreadyExist } - sess := x.NewSession() - defer sess.Close() - if err = sess.Begin(); err != nil { - return nil, err - } - repo := &Repository{ OwnerId: u.Id, Owner: u, @@ -540,116 +535,76 @@ func CreateRepository(u *User, name, desc, lang, license string, private, mirror IsPrivate: private, } + sess := x.NewSession() + defer sessionRelease(sess) + if err = sess.Begin(); err != nil { + return nil, err + } + if _, err = sess.Insert(repo); err != nil { - sess.Rollback() + return nil, err + } else if _, err = sess.Exec("UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?", u.Id); err != nil { return nil, err } - var t *Team // Owner team. + // TODO fix code for mirrors? - mode := WRITABLE - if mirror { - mode = READABLE - } - access := &Access{ - UserName: u.LowerName, - RepoName: path.Join(u.LowerName, repo.LowerName), - Mode: mode, - } // Give access to all members in owner team. if u.IsOrganization() { - t, err = u.GetOwnerTeam() - if err != nil { - sess.Rollback() + if err = repo.recalculateAccesses(sess); err != nil { return nil, err } - if err = t.GetMembers(); err != nil { - sess.Rollback() - return nil, err + + // Update owner team info and count. + t, err := u.getOwnerTeam(sess) + if err != nil { + return nil, fmt.Errorf("get owner team: %v", err) + } else if err = t.getMembers(sess); err != nil { + return nil, fmt.Errorf("get team members: %v", err) } + for _, u := range t.Members { - access.Id = 0 - access.UserName = u.LowerName - if _, err = sess.Insert(access); err != nil { - sess.Rollback() - return nil, err + if err = watchRepo(sess, u.Id, repo.Id, true); err != nil { + return nil, fmt.Errorf("watch repository: %v", err) } } - } else { - if _, err = sess.Insert(access); err != nil { - sess.Rollback() - return nil, err - } - } - if _, err = sess.Exec( - "UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?", u.Id); err != nil { - sess.Rollback() - return nil, err - } - - // Update owner team info and count. - if u.IsOrganization() { t.RepoIds += "$" + com.ToStr(repo.Id) + "|" t.NumRepos++ if _, err = sess.Id(t.Id).AllCols().Update(t); err != nil { - sess.Rollback() return nil, err } - } - - if err = sess.Commit(); err != nil { - return nil, err - } - - if u.IsOrganization() { - t, err := u.GetOwnerTeam() - if err != nil { - log.Error(4, "GetOwnerTeam: %v", err) - } else { - if err = t.GetMembers(); err != nil { - log.Error(4, "GetMembers: %v", err) - } else { - for _, u := range t.Members { - if err = WatchRepo(u.Id, repo.Id, true); err != nil { - log.Error(4, "WatchRepo2: %v", err) - } - } - } - } } else { - if err = WatchRepo(u.Id, repo.Id, true); err != nil { - log.Error(4, "WatchRepo3: %v", err) + if err = watchRepo(sess, u.Id, repo.Id, true); err != nil { + return nil, fmt.Errorf("watch repository 2: %v", err) } } - if err = NewRepoAction(u, repo); err != nil { - log.Error(4, "NewRepoAction: %v", err) + if err = newRepoAction(sess, u, repo); err != nil { + return nil, fmt.Errorf("new repository action: %v", err) } // No need for init mirror. - if mirror { - return repo, nil - } - - repoPath := RepoPath(u.Name, repo.Name) - if err = initRepository(repoPath, u, repo, initReadme, lang, license); err != nil { - if err2 := os.RemoveAll(repoPath); err2 != nil { - log.Error(4, "initRepository: %v", err) - return nil, fmt.Errorf( - "delete repo directory %s/%s failed(2): %v", u.Name, repo.Name, err2) + if !mirror { + repoPath := RepoPath(u.Name, repo.Name) + if err = initRepository(sess, repoPath, u, repo, initReadme, lang, license); err != nil { + if err2 := os.RemoveAll(repoPath); err2 != nil { + log.Error(4, "initRepository: %v", err) + return nil, fmt.Errorf( + "delete repo directory %s/%s failed(2): %v", u.Name, repo.Name, err2) + } + return nil, fmt.Errorf("initRepository: %v", err) } - return nil, fmt.Errorf("initRepository: %v", err) - } - _, stderr, err := process.ExecDir(-1, - repoPath, fmt.Sprintf("CreateRepository(git update-server-info): %s", repoPath), - "git", "update-server-info") - if err != nil { - return nil, errors.New("CreateRepository(git update-server-info): " + stderr) + _, stderr, err := process.ExecDir(-1, + repoPath, fmt.Sprintf("CreateRepository(git update-server-info): %s", repoPath), + "git", "update-server-info") + if err != nil { + return nil, errors.New("CreateRepository(git update-server-info): " + stderr) + } } - return repo, nil + return repo, sess.Commit() } // CountRepositories returns number of repositories. @@ -700,127 +655,39 @@ func TransferOwnership(u *User, newOwner string, repo *Repository) error { } sess := x.NewSession() - defer sess.Close() + defer sessionRelease(sess) if err = sess.Begin(); err != nil { return err } owner := repo.Owner - oldRepoLink := path.Join(owner.LowerName, repo.LowerName) - // Delete all access first if current owner is an organization. - if owner.IsOrganization() { - if _, err = sess.Where("repo_name=?", oldRepoLink).Delete(new(Access)); err != nil { - sess.Rollback() - return fmt.Errorf("fail to delete current accesses: %v", err) - } - } else { - // Delete current owner access. - if _, err = sess.Where("repo_name=?", oldRepoLink).And("user_name=?", owner.LowerName). - Delete(new(Access)); err != nil { - sess.Rollback() - return fmt.Errorf("fail to delete access(owner): %v", err) - } - // In case new owner has access. - if _, err = sess.Where("repo_name=?", oldRepoLink).And("user_name=?", newUser.LowerName). - Delete(new(Access)); err != nil { - sess.Rollback() - return fmt.Errorf("fail to delete access(new user): %v", err) - } - } - - // Change accesses to new repository path. - if _, err = sess.Where("repo_name=?", oldRepoLink). - Update(&Access{RepoName: path.Join(newUser.LowerName, repo.LowerName)}); err != nil { - sess.Rollback() - return fmt.Errorf("fail to update access(change reponame): %v", err) - } // Update repository. repo.OwnerId = newUser.Id + repo.Owner = newUser if _, err := sess.Id(repo.Id).Update(repo); err != nil { - sess.Rollback() return err } // Update user repository number. if _, err = sess.Exec("UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?", newUser.Id); err != nil { - sess.Rollback() return err - } - - if _, err = sess.Exec("UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?", owner.Id); err != nil { - sess.Rollback() + } else if _, err = sess.Exec("UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?", owner.Id); err != nil { return err - } - - mode := WRITABLE - if repo.IsMirror { - mode = READABLE - } - // New owner is organization. - if newUser.IsOrganization() { - access := &Access{ - RepoName: path.Join(newUser.LowerName, repo.LowerName), - Mode: mode, - } - - // Give access to all members in owner team. - t, err := newUser.GetOwnerTeam() - if err != nil { - sess.Rollback() - return err - } - if err = t.GetMembers(); err != nil { - sess.Rollback() - return err - } - for _, u := range t.Members { - access.Id = 0 - access.UserName = u.LowerName - if _, err = sess.Insert(access); err != nil { - sess.Rollback() - return err - } - } - - // Update owner team info and count. - t.RepoIds += "$" + com.ToStr(repo.Id) + "|" - t.NumRepos++ - if _, err = sess.Id(t.Id).AllCols().Update(t); err != nil { - sess.Rollback() - return err - } - } else { - access := &Access{ - RepoName: path.Join(newUser.LowerName, repo.LowerName), - UserName: newUser.LowerName, - Mode: mode, - } - if _, err = sess.Insert(access); err != nil { - sess.Rollback() - return fmt.Errorf("fail to insert access: %v", err) - } - } - - // Change repository directory name. - if err = os.Rename(RepoPath(owner.Name, repo.Name), RepoPath(newUser.Name, repo.Name)); err != nil { - sess.Rollback() + } else if err = repo.recalculateAccesses(sess); err != nil { return err - } - - if err = sess.Commit(); err != nil { + } else if err = watchRepo(sess, newUser.Id, repo.Id, true); err != nil { + return err + } else if err = transferRepoAction(sess, u, newUser, repo); err != nil { return err } - if err = WatchRepo(newUser.Id, repo.Id, true); err != nil { - log.Error(4, "WatchRepo", err) - } - - if err = TransferRepoAction(u, newUser, repo); err != nil { + // Change repository directory name. + if err = os.Rename(RepoPath(owner.Name, repo.Name), RepoPath(newUser.Name, repo.Name)); err != nil { return err } - return nil + return sess.Commit() } // ChangeRepositoryName changes all corresponding setting from old repository name to new one. @@ -832,35 +699,11 @@ func ChangeRepositoryName(userName, oldRepoName, newRepoName string) (err error) return ErrRepoNameIllegal } - // Update accesses. - accesses := make([]Access, 0, 10) - if err = x.Find(&accesses, &Access{RepoName: userName + "/" + oldRepoName}); err != nil { - return err - } - - sess := x.NewSession() - defer sess.Close() - if err = sess.Begin(); err != nil { - return err - } - - for i := range accesses { - accesses[i].RepoName = userName + "/" + newRepoName - if err = UpdateAccessWithSession(sess, &accesses[i]); err != nil { - return err - } - } - // Change repository directory name. - if err = os.Rename(RepoPath(userName, oldRepoName), RepoPath(userName, newRepoName)); err != nil { - sess.Rollback() - return err - } - - return sess.Commit() + return os.Rename(RepoPath(userName, oldRepoName), RepoPath(userName, newRepoName)) } -func UpdateRepository(repo *Repository) error { +func updateRepository(e Engine, repo *Repository) error { repo.LowerName = strings.ToLower(repo.Name) if len(repo.Description) > 255 { @@ -869,10 +712,14 @@ func UpdateRepository(repo *Repository) error { if len(repo.Website) > 255 { repo.Website = repo.Website[:255] } - _, err := x.Id(repo.Id).AllCols().Update(repo) + _, err := e.Id(repo.Id).AllCols().Update(repo) return err } +func UpdateRepository(repo *Repository) error { + return updateRepository(x, repo) +} + // DeleteRepository deletes a repository for a user or organization. func DeleteRepository(uid, repoId int64, userName string) error { repo := &Repository{Id: repoId, OwnerId: uid} @@ -895,21 +742,11 @@ func DeleteRepository(uid, repoId int64, userName string) error { } sess := x.NewSession() - defer sess.Close() + defer sessionRelease(sess) if err = sess.Begin(); err != nil { return err } - if _, err = sess.Delete(&Repository{Id: repoId}); err != nil { - sess.Rollback() - return err - } - - // Delete all access. - if _, err := sess.Delete(&Access{RepoName: strings.ToLower(path.Join(userName, repo.Name))}); err != nil { - sess.Rollback() - return err - } if org.IsOrganization() { idStr := "$" + com.ToStr(repoId) + "|" for _, t := range org.Teams { @@ -919,34 +756,26 @@ func DeleteRepository(uid, repoId int64, userName string) error { t.NumRepos-- t.RepoIds = strings.Replace(t.RepoIds, idStr, "", 1) if _, err = sess.Id(t.Id).AllCols().Update(t); err != nil { - sess.Rollback() return err } } } - if _, err := sess.Delete(&Action{RepoId: repo.Id}); err != nil { - sess.Rollback() + if _, err = sess.Delete(&Repository{Id: repoId}); err != nil { return err - } - if _, err = sess.Delete(&Watch{RepoId: repoId}); err != nil { - sess.Rollback() + } else if _, err := sess.Delete(&Access{RepoID: repo.Id}); err != nil { return err - } - if _, err = sess.Delete(&Mirror{RepoId: repoId}); err != nil { - sess.Rollback() + } else if _, err := sess.Delete(&Action{RepoId: repo.Id}); err != nil { return err - } - if _, err = sess.Delete(&IssueUser{RepoId: repoId}); err != nil { - sess.Rollback() + } else if _, err = sess.Delete(&Watch{RepoId: repoId}); err != nil { return err - } - if _, err = sess.Delete(&Milestone{RepoId: repoId}); err != nil { - sess.Rollback() + } else if _, err = sess.Delete(&Mirror{RepoId: repoId}); err != nil { return err - } - if _, err = sess.Delete(&Release{RepoId: repoId}); err != nil { - sess.Rollback() + } else if _, err = sess.Delete(&IssueUser{RepoId: repoId}); err != nil { + return err + } else if _, err = sess.Delete(&Milestone{RepoId: repoId}); err != nil { + return err + } else if _, err = sess.Delete(&Release{RepoId: repoId}); err != nil { return err } @@ -954,29 +783,24 @@ func DeleteRepository(uid, repoId int64, userName string) error { if err = x.Iterate(&Issue{RepoId: repoId}, func(idx int, bean interface{}) error { issue := bean.(*Issue) if _, err = sess.Delete(&Comment{IssueId: issue.Id}); err != nil { - sess.Rollback() return err } return nil }); err != nil { - sess.Rollback() return err } if _, err = sess.Delete(&Issue{RepoId: repoId}); err != nil { - sess.Rollback() return err } if repo.IsFork { if _, err = sess.Exec("UPDATE `repository` SET num_forks = num_forks - 1 WHERE id = ?", repo.ForkId); err != nil { - sess.Rollback() return err } } if _, err = sess.Exec("UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?", uid); err != nil { - sess.Rollback() return err } @@ -988,6 +812,7 @@ func DeleteRepository(uid, repoId int64, userName string) error { log.Error(4, "Fail to add notice: %v", err) } } + return sess.Commit() } @@ -1026,10 +851,9 @@ func GetRepositoryByName(uid int64, repoName string) (*Repository, error) { return repo, err } -// GetRepositoryById returns the repository by given id if exists. -func GetRepositoryById(id int64) (*Repository, error) { +func getRepositoryById(e Engine, id int64) (*Repository, error) { repo := &Repository{} - has, err := x.Id(id).Get(repo) + has, err := e.Id(id).Get(repo) if err != nil { return nil, err } else if !has { @@ -1038,6 +862,11 @@ func GetRepositoryById(id int64) (*Repository, error) { return repo, nil } +// GetRepositoryById returns the repository by given id if exists. +func GetRepositoryById(id int64) (*Repository, error) { + return getRepositoryById(x, id) +} + // GetRepositories returns a list of repositories of given user. func GetRepositories(uid int64, private bool) ([]*Repository, error) { repos := make([]*Repository, 0, 10) @@ -1061,73 +890,6 @@ func GetRepositoryCount(user *User) (int64, error) { return x.Count(&Repository{OwnerId: user.Id}) } -// GetCollaboratorNames returns a list of user name of repository's collaborators. -func GetCollaboratorNames(repoName string) ([]string, error) { - accesses := make([]*Access, 0, 10) - if err := x.Find(&accesses, &Access{RepoName: strings.ToLower(repoName)}); err != nil { - return nil, err - } - - names := make([]string, len(accesses)) - for i := range accesses { - names[i] = accesses[i].UserName - } - return names, nil -} - -// CollaborativeRepository represents a repository with collaborative information. -type CollaborativeRepository struct { - *Repository - CanPush bool -} - -// GetCollaborativeRepos returns a list of repositories that user is collaborator. -func GetCollaborativeRepos(uname string) ([]*CollaborativeRepository, error) { - uname = strings.ToLower(uname) - accesses := make([]*Access, 0, 10) - if err := x.Find(&accesses, &Access{UserName: uname}); err != nil { - return nil, err - } - - repos := make([]*CollaborativeRepository, 0, 10) - for _, access := range accesses { - infos := strings.Split(access.RepoName, "/") - if infos[0] == uname { - continue - } - - u, err := GetUserByName(infos[0]) - if err != nil { - return nil, err - } - - repo, err := GetRepositoryByName(u.Id, infos[1]) - if err != nil { - return nil, err - } - repo.Owner = u - repos = append(repos, &CollaborativeRepository{repo, access.Mode == WRITABLE}) - } - return repos, nil -} - -// GetCollaborators returns a list of users of repository's collaborators. -func GetCollaborators(repoName string) (us []*User, err error) { - accesses := make([]*Access, 0, 10) - if err = x.Find(&accesses, &Access{RepoName: strings.ToLower(repoName)}); err != nil { - return nil, err - } - - us = make([]*User, len(accesses)) - for i := range accesses { - us[i], err = GetUserByName(accesses[i].UserName) - if err != nil { - return nil, err - } - } - return us, nil -} - type SearchOption struct { Keyword string Uid int64 @@ -1275,6 +1037,94 @@ func GitGcRepos() error { }) } +// _________ .__ .__ ___. __ .__ +// \_ ___ \ ____ | | | | _____ \_ |__ ________________ _/ |_|__| ____ ____ +// / \ \/ / _ \| | | | \__ \ | __ \ / _ \_ __ \__ \\ __\ |/ _ \ / \ +// \ \___( <_> ) |_| |__/ __ \| \_\ ( <_> ) | \// __ \| | | ( <_> ) | \ +// \______ /\____/|____/____(____ /___ /\____/|__| (____ /__| |__|\____/|___| / +// \/ \/ \/ \/ \/ + +// A Collaboration is a relation between an individual and a repository +type Collaboration struct { + ID int64 `xorm:"pk autoincr"` + RepoID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"` + UserID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"` + Created time.Time `xorm:"CREATED"` +} + +// Add collaborator and accompanying access +func (repo *Repository) AddCollaborator(u *User) error { + collaboration := &Collaboration{ + RepoID: repo.Id, + UserID: u.Id, + } + + has, err := x.Get(collaboration) + if err != nil { + return err + } else if has { + return nil + } + + sess := x.NewSession() + defer sessionRelease(sess) + if err = sess.Begin(); err != nil { + return err + } + + if _, err = sess.InsertOne(collaboration); err != nil { + return err + } else if err = repo.recalculateAccesses(sess); err != nil { + return err + } + + return sess.Commit() +} + +func (repo *Repository) getCollaborators(e Engine) ([]*User, error) { + collaborations := make([]*Collaboration, 0) + if err := e.Find(&collaborations, &Collaboration{RepoID: repo.Id}); err != nil { + return nil, err + } + + users := make([]*User, len(collaborations)) + for i, c := range collaborations { + user, err := getUserById(e, c.UserID) + if err != nil { + return nil, err + } + users[i] = user + } + return users, nil +} + +// GetCollaborators returns the collaborators for a repository +func (repo *Repository) GetCollaborators() ([]*User, error) { + return repo.getCollaborators(x) +} + +// Delete collaborator and accompanying access +func (repo *Repository) DeleteCollaborator(u *User) (err error) { + collaboration := &Collaboration{ + RepoID: repo.Id, + UserID: u.Id, + } + + sess := x.NewSession() + defer sessionRelease(sess) + 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() +} + // __ __ __ .__ // / \ / \_____ _/ |_ ____ | |__ // \ \/\/ /\__ \\ __\/ ___\| | \ @@ -1321,25 +1171,28 @@ func WatchRepo(uid, repoId int64, watch bool) (err error) { return watchRepo(x, uid, repoId, watch) } -// GetWatchers returns all watchers of given repository. -func GetWatchers(rid int64) ([]*Watch, error) { +func getWatchers(e Engine, rid int64) ([]*Watch, error) { watches := make([]*Watch, 0, 10) - err := x.Find(&watches, &Watch{RepoId: rid}) + err := e.Find(&watches, &Watch{RepoId: rid}) return watches, err } -// NotifyWatchers creates batch of actions for every watcher. -func NotifyWatchers(act *Action) error { +// GetWatchers returns all watchers of given repository. +func GetWatchers(rid int64) ([]*Watch, error) { + return getWatchers(x, rid) +} + +func notifyWatchers(e Engine, act *Action) error { // Add feeds for user self and all watchers. - watches, err := GetWatchers(act.RepoId) + watches, err := getWatchers(e, act.RepoId) if err != nil { - return errors.New("repo.NotifyWatchers(get watches): " + err.Error()) + return fmt.Errorf("get watchers: %v", err) } // Add feed for actioner. act.UserId = act.ActUserId - if _, err = x.InsertOne(act); err != nil { - return errors.New("repo.NotifyWatchers(create action): " + err.Error()) + if _, err = e.InsertOne(act); err != nil { + return fmt.Errorf("insert new actioner: %v", err) } for i := range watches { @@ -1349,13 +1202,18 @@ func NotifyWatchers(act *Action) error { act.Id = 0 act.UserId = watches[i].UserId - if _, err = x.InsertOne(act); err != nil { - return errors.New("repo.NotifyWatchers(create action): " + err.Error()) + if _, err = e.InsertOne(act); err != nil { + return fmt.Errorf("insert new action: %v", err) } } return nil } +// NotifyWatchers creates batch of actions for every watcher. +func NotifyWatchers(act *Action) error { + return notifyWatchers(x, act) +} + // _________ __ // / _____// |______ _______ // \_____ \\ __\__ \\_ __ \ @@ -1424,12 +1282,6 @@ func ForkRepository(u *User, oldRepo *Repository, name, desc string) (*Repositor } } - sess := x.NewSession() - defer sess.Close() - if err = sess.Begin(); err != nil { - return nil, err - } - repo := &Repository{ OwnerId: u.Id, Owner: u, @@ -1441,101 +1293,59 @@ func ForkRepository(u *User, oldRepo *Repository, name, desc string) (*Repositor ForkId: oldRepo.Id, } - if _, err = sess.Insert(repo); err != nil { - sess.Rollback() + sess := x.NewSession() + defer sessionRelease(sess) + if err = sess.Begin(); err != nil { return nil, err } - var t *Team // Owner team. - - mode := WRITABLE + if _, err = sess.Insert(repo); err != nil { + return nil, err + } - access := &Access{ - UserName: u.LowerName, - RepoName: path.Join(u.LowerName, repo.LowerName), - Mode: mode, + if err = repo.recalculateAccesses(sess); err != nil { + return nil, err + } else if _, err = sess.Exec("UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?", u.Id); err != nil { + return nil, err } - // Give access to all members in owner team. + if u.IsOrganization() { - t, err = u.GetOwnerTeam() + // Update owner team info and count. + t, err := u.getOwnerTeam(sess) if err != nil { - sess.Rollback() - return nil, err - } - if err = t.GetMembers(); err != nil { - sess.Rollback() - return nil, err + return nil, fmt.Errorf("get owner team: %v", err) + } else if err = t.getMembers(sess); err != nil { + return nil, fmt.Errorf("get team members: %v", err) } + for _, u := range t.Members { - access.Id = 0 - access.UserName = u.LowerName - if _, err = sess.Insert(access); err != nil { - sess.Rollback() - return nil, err + if err = watchRepo(sess, u.Id, repo.Id, true); err != nil { + return nil, fmt.Errorf("watch repository: %v", err) } } - } else { - if _, err = sess.Insert(access); err != nil { - sess.Rollback() - return nil, err - } - } - if _, err = sess.Exec( - "UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?", u.Id); err != nil { - sess.Rollback() - return nil, err - } - - // Update owner team info and count. - if u.IsOrganization() { t.RepoIds += "$" + com.ToStr(repo.Id) + "|" t.NumRepos++ if _, err = sess.Id(t.Id).AllCols().Update(t); err != nil { - sess.Rollback() return nil, err } - } - - if u.IsOrganization() { - t, err := u.GetOwnerTeam() - if err != nil { - log.Error(4, "GetOwnerTeam: %v", err) - } else { - if err = t.GetMembers(); err != nil { - log.Error(4, "GetMembers: %v", err) - } else { - for _, u := range t.Members { - if err = watchRepo(sess, u.Id, repo.Id, true); err != nil { - log.Error(4, "WatchRepo2: %v", err) - } - } - } - } } else { if err = watchRepo(sess, u.Id, repo.Id, true); err != nil { - log.Error(4, "WatchRepo3: %v", err) + return nil, fmt.Errorf("watch repository 2: %v", err) } } - if err = NewRepoAction(u, repo); err != nil { - log.Error(4, "NewRepoAction: %v", err) + if err = newRepoAction(sess, u, repo); err != nil { + return nil, fmt.Errorf("new repository action: %v", err) } - if _, err = sess.Exec( - "UPDATE `repository` SET num_forks = num_forks + 1 WHERE id = ?", oldRepo.Id); err != nil { - sess.Rollback() + if _, err = sess.Exec("UPDATE `repository` SET num_forks = num_forks + 1 WHERE id = ?", oldRepo.Id); err != nil { return nil, err } oldRepoPath, err := oldRepo.RepoPath() if err != nil { - sess.Rollback() - return nil, fmt.Errorf("fail to get repo path(%s): %v", oldRepo.Name, err) - } - - if err = sess.Commit(); err != nil { - return nil, err + return nil, fmt.Errorf("get old repository path: %v", err) } repoPath := RepoPath(u.Name, repo.Name) @@ -1543,15 +1353,15 @@ func ForkRepository(u *User, oldRepo *Repository, name, desc string) (*Repositor fmt.Sprintf("ForkRepository(git clone): %s/%s", u.Name, repo.Name), "git", "clone", "--bare", oldRepoPath, repoPath) if err != nil { - return nil, errors.New("ForkRepository(git clone): " + stderr) + return nil, fmt.Errorf("git clone: %v", stderr) } _, stderr, err = process.ExecDir(-1, repoPath, fmt.Sprintf("ForkRepository(git update-server-info): %s", repoPath), "git", "update-server-info") if err != nil { - return nil, errors.New("ForkRepository(git update-server-info): " + stderr) + return nil, fmt.Errorf("git update-server-info: %v", err) } - return repo, nil + return repo, sess.Commit() } diff --git a/models/user.go b/models/user.go index a974e081f1..387ab6555b 100644 --- a/models/user.go +++ b/models/user.go @@ -398,63 +398,7 @@ func ChangeUserName(u *User, newUserName string) (err error) { return ErrUserNameIllegal } - newUserName = strings.ToLower(newUserName) - if u.LowerName == newUserName { - // User only change letter cases. - return nil - } - - // Update accesses of user. - accesses := make([]Access, 0, 10) - if err = x.Find(&accesses, &Access{UserName: u.LowerName}); err != nil { - return err - } - - sess := x.NewSession() - defer sess.Close() - if err = sess.Begin(); err != nil { - return err - } - - for i := range accesses { - accesses[i].UserName = newUserName - if strings.HasPrefix(accesses[i].RepoName, u.LowerName+"/") { - accesses[i].RepoName = strings.Replace(accesses[i].RepoName, u.LowerName, newUserName, 1) - } - if err = UpdateAccessWithSession(sess, &accesses[i]); err != nil { - return err - } - } - - repos, err := GetRepositories(u.Id, true) - if err != nil { - return err - } - for i := range repos { - accesses = make([]Access, 0, 10) - // Update accesses of user repository. - if err = x.Find(&accesses, &Access{RepoName: u.LowerName + "/" + repos[i].LowerName}); err != nil { - return err - } - - for j := range accesses { - // if the access is not the user's access (already updated above) - if accesses[j].UserName != u.LowerName { - accesses[j].RepoName = newUserName + "/" + repos[i].LowerName - if err = UpdateAccessWithSession(sess, &accesses[j]); err != nil { - return err - } - } - } - } - - // Change user directory name. - if err = os.Rename(UserPath(u.LowerName), UserPath(newUserName)); err != nil { - sess.Rollback() - return err - } - - return sess.Commit() + return os.Rename(UserPath(u.LowerName), UserPath(newUserName)) } // UpdateUser updates user's information. @@ -527,7 +471,7 @@ func DeleteUser(u *User) error { return err } // Delete all accesses. - if _, err = x.Delete(&Access{UserName: u.LowerName}); err != nil { + if _, err = x.Delete(&Access{UserID: u.Id}); err != nil { return err } // Delete all alternative email addresses @@ -570,8 +514,7 @@ func UserPath(userName string) string { func GetUserByKeyId(keyId int64) (*User, error) { user := new(User) - rawSql := "SELECT a.* FROM `user` AS a, public_key AS b WHERE a.id = b.owner_id AND b.id=?" - has, err := x.Sql(rawSql, keyId).Get(user) + has, err := x.Sql("SELECT a.* FROM `user` AS a, public_key AS b WHERE a.id = b.owner_id AND b.id=?", keyId).Get(user) if err != nil { return nil, err } else if !has { @@ -580,10 +523,9 @@ func GetUserByKeyId(keyId int64) (*User, error) { return user, nil } -// GetUserById returns the user object by given ID if exists. -func GetUserById(id int64) (*User, error) { +func getUserById(e Engine, id int64) (*User, error) { u := new(User) - has, err := x.Id(id).Get(u) + has, err := e.Id(id).Get(u) if err != nil { return nil, err } else if !has { @@ -592,6 +534,11 @@ func GetUserById(id int64) (*User, error) { return u, nil } +// GetUserById returns the user object by given ID if exists. +func GetUserById(id int64) (*User, error) { + return getUserById(x, id) +} + // GetUserByName returns user by given name. func GetUserByName(name string) (*User, error) { if len(name) == 0 { diff --git a/modules/middleware/org.go b/modules/middleware/org.go index e687258617..0e544fe4a2 100644 --- a/modules/middleware/org.go +++ b/modules/middleware/org.go @@ -87,7 +87,7 @@ func OrgAssignment(redirect bool, args ...bool) macaron.Handler { return } ctx.Data["Team"] = ctx.Org.Team - ctx.Org.IsAdminTeam = ctx.Org.Team.IsOwnerTeam() || ctx.Org.Team.Authorize == models.ORG_ADMIN + ctx.Org.IsAdminTeam = ctx.Org.Team.IsOwnerTeam() || ctx.Org.Team.Authorize >= models.ACCESS_MODE_ADMIN } ctx.Data["IsAdminTeam"] = ctx.Org.IsAdminTeam if requireAdminTeam && !ctx.Org.IsAdminTeam { diff --git a/modules/middleware/repo.go b/modules/middleware/repo.go index 67a9eda691..8188deb534 100644 --- a/modules/middleware/repo.go +++ b/modules/middleware/repo.go @@ -5,7 +5,6 @@ package middleware import ( - "errors" "fmt" "net/url" "strings" @@ -29,17 +28,10 @@ func ApiRepoAssignment() macaron.Handler { err error ) - // Collaborators who have write access can be seen as owners. - if ctx.IsSigned { - ctx.Repo.IsOwner, err = models.HasAccess(ctx.User.Name, userName+"/"+repoName, models.WRITABLE) - if err != nil { - ctx.JSON(500, &base.ApiJsonErr{"HasAccess: " + err.Error(), base.DOC_URL}) - return - } - ctx.Repo.IsTrueOwner = ctx.User.LowerName == strings.ToLower(userName) - } - - if !ctx.Repo.IsTrueOwner { + // Check if the user is the same as the repository owner. + if ctx.IsSigned && ctx.User.LowerName == strings.ToLower(userName) { + u = ctx.User + } else { u, err = models.GetUserByName(userName) if err != nil { if err == models.ErrUserNotExist { @@ -49,64 +41,39 @@ func ApiRepoAssignment() macaron.Handler { } return } - } else { - u = ctx.User } ctx.Repo.Owner = u - // Organization owner team members are true owners as well. - if ctx.IsSigned && ctx.Repo.Owner.IsOrganization() && ctx.Repo.Owner.IsOwnedBy(ctx.User.Id) { - ctx.Repo.IsTrueOwner = true - } - // Get repository. repo, err := models.GetRepositoryByName(u.Id, repoName) if err != nil { if err == models.ErrRepoNotExist { ctx.Error(404) - return + } else { + ctx.JSON(500, &base.ApiJsonErr{"GetRepositoryByName: " + err.Error(), base.DOC_URL}) } - ctx.JSON(500, &base.ApiJsonErr{"GetRepositoryByName: " + err.Error(), base.DOC_URL}) return } else if err = repo.GetOwner(); err != nil { ctx.JSON(500, &base.ApiJsonErr{"GetOwner: " + err.Error(), base.DOC_URL}) return } - // Check if the mirror repository owner(mirror repository doesn't have access). - if ctx.IsSigned && !ctx.Repo.IsOwner { - if repo.OwnerId == ctx.User.Id { - ctx.Repo.IsOwner = true - } - // Check if current user has admin permission to repository. - if u.IsOrganization() { - auth, err := models.GetHighestAuthorize(u.Id, ctx.User.Id, repo.Id, 0) - if err != nil { - ctx.JSON(500, &base.ApiJsonErr{"GetHighestAuthorize: " + err.Error(), base.DOC_URL}) - return - } - if auth == models.ORG_ADMIN { - ctx.Repo.IsOwner = true - ctx.Repo.IsAdmin = true - } + if ctx.IsSigned { + mode, err := models.AccessLevel(ctx.User, repo) + if err != nil { + ctx.JSON(500, &base.ApiJsonErr{"AccessLevel: " + err.Error(), base.DOC_URL}) + return } + + ctx.Repo.IsOwner = mode >= models.ACCESS_MODE_WRITE + ctx.Repo.IsAdmin = mode >= models.ACCESS_MODE_READ + ctx.Repo.IsTrueOwner = mode >= models.ACCESS_MODE_OWNER } // Check access. if repo.IsPrivate && !ctx.Repo.IsOwner { - if ctx.User == nil { - ctx.Error(404) - return - } - - hasAccess, err := models.HasAccess(ctx.User.Name, ctx.Repo.Owner.Name+"/"+repo.Name, models.READABLE) - if err != nil { - ctx.JSON(500, &base.ApiJsonErr{"HasAccess: " + err.Error(), base.DOC_URL}) - return - } else if !hasAccess { - ctx.Error(404) - return - } + ctx.Error(404) + return } ctx.Repo.HasAccess = true @@ -242,101 +209,57 @@ func RepoAssignment(redirect bool, args ...bool) macaron.Handler { refName = ctx.Params(":path") } - // Collaborators who have write access can be seen as owners. - if ctx.IsSigned { - ctx.Repo.IsOwner, err = models.HasAccess(ctx.User.Name, userName+"/"+repoName, models.WRITABLE) - if err != nil { - ctx.Handle(500, "HasAccess", err) - return - } - ctx.Repo.IsTrueOwner = ctx.User.LowerName == strings.ToLower(userName) - } - - if !ctx.Repo.IsTrueOwner { + // Check if the user is the same as the repository owner + if ctx.IsSigned && ctx.User.LowerName == strings.ToLower(userName) { + u = ctx.User + } else { u, err = models.GetUserByName(userName) if err != nil { if err == models.ErrUserNotExist { ctx.Handle(404, "GetUserByName", err) - } else if redirect { - log.Error(4, "GetUserByName", err) - ctx.Redirect(setting.AppSubUrl + "/") } else { ctx.Handle(500, "GetUserByName", err) } return } - } else { - u = ctx.User - } - - if u == nil { - if redirect { - ctx.Redirect(setting.AppSubUrl + "/") - return - } - ctx.Handle(404, "RepoAssignment", errors.New("invliad user account for single repository")) - return } ctx.Repo.Owner = u - // Organization owner team members are true owners as well. - if ctx.IsSigned && ctx.Repo.Owner.IsOrganization() && ctx.Repo.Owner.IsOwnedBy(ctx.User.Id) { - ctx.Repo.IsTrueOwner = true - } - // Get repository. repo, err := models.GetRepositoryByName(u.Id, repoName) if err != nil { if err == models.ErrRepoNotExist { ctx.Handle(404, "GetRepositoryByName", err) - return - } else if redirect { - ctx.Redirect(setting.AppSubUrl + "/") - return + } else { + ctx.Handle(500, "GetRepositoryByName", err) } - ctx.Handle(500, "GetRepositoryByName", err) return } else if err = repo.GetOwner(); err != nil { ctx.Handle(500, "GetOwner", err) return } - // Check if the mirror repository owner(mirror repository doesn't have access). - if ctx.IsSigned && !ctx.Repo.IsOwner { - if repo.OwnerId == ctx.User.Id { - ctx.Repo.IsOwner = true + if ctx.IsSigned { + mode, err := models.AccessLevel(ctx.User, repo) + if err != nil { + ctx.Handle(500, "AccessLevel", err) + return } - // Check if current user has admin permission to repository. - if u.IsOrganization() { - auth, err := models.GetHighestAuthorize(u.Id, ctx.User.Id, repo.Id, 0) - if err != nil { - ctx.Handle(500, "GetHighestAuthorize", err) - return - } - if auth == models.ORG_ADMIN { - ctx.Repo.IsOwner = true - ctx.Repo.IsAdmin = true - } + ctx.Repo.IsOwner = mode >= models.ACCESS_MODE_WRITE + ctx.Repo.IsAdmin = mode >= models.ACCESS_MODE_READ + ctx.Repo.IsTrueOwner = mode >= models.ACCESS_MODE_OWNER + if !ctx.Repo.IsTrueOwner && ctx.Repo.Owner.IsOrganization() { + ctx.Repo.IsTrueOwner = ctx.Repo.Owner.IsOwnedBy(ctx.User.Id) } } // Check access. if repo.IsPrivate && !ctx.Repo.IsOwner { - if ctx.User == nil { - ctx.Handle(404, "HasAccess", nil) - return - } - - hasAccess, err := models.HasAccess(ctx.User.Name, ctx.Repo.Owner.Name+"/"+repo.Name, models.READABLE) - if err != nil { - ctx.Handle(500, "HasAccess", err) - return - } else if !hasAccess { - ctx.Handle(404, "HasAccess", nil) - return - } + ctx.Handle(404, "no access right", err) + return } ctx.Repo.HasAccess = true + ctx.Data["HasAccess"] = true if repo.IsMirror { diff --git a/modules/setting/setting.go b/modules/setting/setting.go index 52dca3f041..6a36105691 100644 --- a/modules/setting/setting.go +++ b/modules/setting/setting.go @@ -67,6 +67,11 @@ var ( CookieRememberName string ReverseProxyAuthUser string + // Database settings. + UseSQLite3 bool + UseMySQL bool + UsePostgreSQL bool + // Webhook settings. Webhook struct { TaskInterval int diff --git a/routers/api/v1/repo.go b/routers/api/v1/repo.go index fde184d994..eb9908911f 100644 --- a/routers/api/v1/repo.go +++ b/routers/api/v1/repo.go @@ -238,28 +238,31 @@ func ListMyRepos(ctx *middleware.Context) { } numOwnRepos := len(ownRepos) - collaRepos, err := models.GetCollaborativeRepos(ctx.User.Name) + accessibleRepos, err := ctx.User.GetAccessibleRepositories() if err != nil { - ctx.JSON(500, &base.ApiJsonErr{"GetCollaborativeRepos: " + err.Error(), base.DOC_URL}) + ctx.JSON(500, &base.ApiJsonErr{"GetAccessibleRepositories: " + err.Error(), base.DOC_URL}) return } - repos := make([]*api.Repository, numOwnRepos+len(collaRepos)) + repos := make([]*api.Repository, numOwnRepos+len(accessibleRepos)) for i := range ownRepos { repos[i] = ToApiRepository(ctx.User, ownRepos[i], api.Permission{true, true, true}) } - for i := range collaRepos { - if err = collaRepos[i].GetOwner(); err != nil { + i := numOwnRepos + + for repo, access := range accessibleRepos { + if err = repo.GetOwner(); err != nil { ctx.JSON(500, &base.ApiJsonErr{"GetOwner: " + err.Error(), base.DOC_URL}) return } - j := i + numOwnRepos - repos[j] = ToApiRepository(collaRepos[i].Owner, collaRepos[i].Repository, api.Permission{false, collaRepos[i].CanPush, true}) + + repos[i] = ToApiRepository(repo.Owner, repo, api.Permission{false, access >= models.ACCESS_MODE_WRITE, true}) // FIXME: cache result to reduce DB query? - if collaRepos[i].Owner.IsOrganization() && collaRepos[i].Owner.IsOwnedBy(ctx.User.Id) { - repos[j].Permissions.Admin = true + if repo.Owner.IsOrganization() && repo.Owner.IsOwnedBy(ctx.User.Id) { + repos[i].Permissions.Admin = true } + i++ } ctx.JSON(200, &repos) diff --git a/routers/org/teams.go b/routers/org/teams.go index 9dd9b8e229..2fbb1480d1 100644 --- a/routers/org/teams.go +++ b/routers/org/teams.go @@ -165,14 +165,14 @@ func NewTeamPost(ctx *middleware.Context, form auth.CreateTeamForm) { } // Validate permission level. - var auth models.AuthorizeType + var auth models.AccessMode switch form.Permission { case "read": - auth = models.ORG_READABLE + auth = models.ACCESS_MODE_READ case "write": - auth = models.ORG_WRITABLE + auth = models.ACCESS_MODE_WRITE case "admin": - auth = models.ORG_ADMIN + auth = models.ACCESS_MODE_ADMIN default: ctx.Error(401) return @@ -246,14 +246,14 @@ func EditTeamPost(ctx *middleware.Context, form auth.CreateTeamForm) { isAuthChanged := false if !t.IsOwnerTeam() { // Validate permission level. - var auth models.AuthorizeType + var auth models.AccessMode switch form.Permission { case "read": - auth = models.ORG_READABLE + auth = models.ACCESS_MODE_READ case "write": - auth = models.ORG_WRITABLE + auth = models.ACCESS_MODE_WRITE case "admin": - auth = models.ORG_ADMIN + auth = models.ACCESS_MODE_ADMIN default: ctx.Error(401) return diff --git a/routers/repo/http.go b/routers/repo/http.go index f5dc0c9d6a..034b5a7b5e 100644 --- a/routers/repo/http.go +++ b/routers/repo/http.go @@ -137,18 +137,18 @@ func Http(ctx *middleware.Context) { } if !isPublicPull { - var tp = models.WRITABLE + var tp = models.ACCESS_MODE_WRITE if isPull { - tp = models.READABLE + tp = models.ACCESS_MODE_READ } - has, err := models.HasAccess(authUsername, username+"/"+reponame, tp) + has, err := models.HasAccess(authUser, repo, tp) if err != nil { ctx.Handle(401, "no basic auth and digit auth", nil) return } else if !has { - if tp == models.READABLE { - has, err = models.HasAccess(authUsername, username+"/"+reponame, models.WRITABLE) + if tp == models.ACCESS_MODE_READ { + has, err = models.HasAccess(authUser, repo, models.ACCESS_MODE_WRITE) if err != nil || !has { ctx.Handle(401, "no basic auth and digit auth", nil) return diff --git a/routers/repo/issue.go b/routers/repo/issue.go index 3e0206dafb..bf39d9aba6 100644 --- a/routers/repo/issue.go +++ b/routers/repo/issue.go @@ -174,7 +174,7 @@ func CreateIssue(ctx *middleware.Context) { return } - us, err := models.GetCollaborators(strings.TrimPrefix(ctx.Repo.RepoLink, "/")) + us, err := ctx.Repo.Repository.GetCollaborators() if err != nil { ctx.Handle(500, "issue.CreateIssue(GetCollaborators)", err) return @@ -218,7 +218,7 @@ func CreateIssuePost(ctx *middleware.Context, form auth.CreateIssueForm) { return } - _, err = models.GetCollaborators(strings.TrimPrefix(ctx.Repo.RepoLink, "/")) + _, err = ctx.Repo.Repository.GetCollaborators() if err != nil { send(500, nil, err) return @@ -246,8 +246,8 @@ func CreateIssuePost(ctx *middleware.Context, form auth.CreateIssueForm) { if err := models.NewIssue(issue); err != nil { send(500, nil, err) return - } else if err := models.NewIssueUserPairs(issue.RepoId, issue.Id, ctx.Repo.Owner.Id, - ctx.User.Id, form.AssigneeId, ctx.Repo.Repository.Name); err != nil { + } else if err := models.NewIssueUserPairs(ctx.Repo.Repository, issue.Id, ctx.Repo.Owner.Id, + ctx.User.Id, form.AssigneeId); err != nil { send(500, nil, err) return } @@ -384,7 +384,7 @@ func ViewIssue(ctx *middleware.Context) { } // Get all collaborators. - ctx.Data["Collaborators"], err = models.GetCollaborators(strings.TrimPrefix(ctx.Repo.RepoLink, "/")) + ctx.Data["Collaborators"], err = ctx.Repo.Repository.GetCollaborators() if err != nil { ctx.Handle(500, "issue.CreateIssue(GetCollaborators)", err) return diff --git a/routers/repo/setting.go b/routers/repo/setting.go index b40ef2d9ae..0f8acfa5ba 100644 --- a/routers/repo/setting.go +++ b/routers/repo/setting.go @@ -169,22 +169,12 @@ func SettingsCollaboration(ctx *middleware.Context) { ctx.Data["Title"] = ctx.Tr("repo.settings") ctx.Data["PageIsSettingsCollaboration"] = true - repoLink := path.Join(ctx.Repo.Owner.LowerName, ctx.Repo.Repository.LowerName) - if ctx.Req.Method == "POST" { name := strings.ToLower(ctx.Query("collaborator")) if len(name) == 0 || ctx.Repo.Owner.LowerName == name { ctx.Redirect(setting.AppSubUrl + ctx.Req.URL.Path) return } - has, err := models.HasAccess(name, repoLink, models.WRITABLE) - if err != nil { - ctx.Handle(500, "HasAccess", err) - return - } else if has { - ctx.Redirect(setting.AppSubUrl + ctx.Req.URL.Path) - return - } u, err := models.GetUserByName(name) if err != nil { @@ -204,9 +194,8 @@ func SettingsCollaboration(ctx *middleware.Context) { return } - if err = models.AddAccess(&models.Access{UserName: name, RepoName: repoLink, - Mode: models.WRITABLE}); err != nil { - ctx.Handle(500, "AddAccess", err) + if err = ctx.Repo.Repository.AddCollaborator(u); err != nil { + ctx.Handle(500, "AddCollaborator", err) return } @@ -225,50 +214,27 @@ func SettingsCollaboration(ctx *middleware.Context) { // Delete collaborator. remove := strings.ToLower(ctx.Query("remove")) if len(remove) > 0 && remove != ctx.Repo.Owner.LowerName { - needDelete := true - if ctx.User.IsOrganization() { - // Check if user belongs to a team that has access to this repository. - auth, err := models.GetHighestAuthorize(ctx.Repo.Owner.Id, ctx.User.Id, ctx.Repo.Repository.Id, 0) - if err != nil { - ctx.Handle(500, "GetHighestAuthorize", err) - return - } - if auth > 0 { - needDelete = false - } + u, err := models.GetUserByName(remove) + if err != nil { + ctx.Handle(500, "GetUserByName", err) + return } - - if needDelete { - if err := models.DeleteAccess(&models.Access{UserName: remove, RepoName: repoLink}); err != nil { - ctx.Handle(500, "DeleteAccess", err) - return - } + if err := ctx.Repo.Repository.DeleteCollaborator(u); err != nil { + ctx.Handle(500, "DeleteCollaborator", err) + return } ctx.Flash.Success(ctx.Tr("repo.settings.remove_collaborator_success")) ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration") return } - names, err := models.GetCollaboratorNames(repoLink) + users, err := ctx.Repo.Repository.GetCollaborators() if err != nil { ctx.Handle(500, "GetCollaborators", err) return } - collaborators := make([]*models.User, 0, len(names)) - for _, name := range names { - u, err := models.GetUserByName(name) - if err != nil { - ctx.Handle(500, "GetUserByName", err) - return - } - // Does not show organization members. - if ctx.Repo.Owner.IsOrganization() && ctx.Repo.Owner.IsOrgMember(u.Id) { - continue - } - collaborators = append(collaborators, u) - } - ctx.Data["Collaborators"] = collaborators + ctx.Data["Collaborators"] = users ctx.HTML(200, COLLABORATION) } diff --git a/routers/user/home.go b/routers/user/home.go index 1aabe08774..35407534f9 100644 --- a/routers/user/home.go +++ b/routers/user/home.go @@ -49,13 +49,19 @@ func Dashboard(ctx *middleware.Context) { } else { // Normal user. ctxUser = ctx.User - collaborates, err := models.GetCollaborativeRepos(ctxUser.Name) + collaborates, err := ctx.User.GetAccessibleRepositories() if err != nil { - ctx.Handle(500, "GetCollaborativeRepos", err) + ctx.Handle(500, "GetAccessibleRepositories", err) return } - ctx.Data["CollaborateCount"] = len(collaborates) - ctx.Data["CollaborativeRepos"] = collaborates + + repositories := make([]*models.Repository, 0, len(collaborates)) + for repo := range collaborates { + repositories = append(repositories, repo) + } + + ctx.Data["CollaborateCount"] = len(repositories) + ctx.Data["CollaborativeRepos"] = repositories } ctx.Data["ContextUser"] = ctxUser @@ -97,8 +103,7 @@ func Dashboard(ctx *middleware.Context) { feeds := make([]*models.Action, 0, len(actions)) for _, act := range actions { if act.IsPrivate { - if has, _ := models.HasAccess(ctx.User.Name, act.RepoUserName+"/"+act.RepoName, - models.READABLE); !has { + if has, _ := models.HasAccess(ctx.User, &models.Repository{Id: act.RepoId, IsPrivate: true}, models.ACCESS_MODE_READ); !has { continue } } @@ -205,8 +210,11 @@ func Profile(ctx *middleware.Context) { if !ctx.IsSigned { continue } - if has, _ := models.HasAccess(ctx.User.Name, act.RepoUserName+"/"+act.RepoName, - models.READABLE); !has { + if has, _ := models.HasAccess(ctx.User, + &models.Repository{ + Id: act.RepoId, + IsPrivate: true, + }, models.ACCESS_MODE_READ); !has { continue } } diff --git a/templates/.VERSION b/templates/.VERSION index b9cd4a186a..056f3141af 100644 --- a/templates/.VERSION +++ b/templates/.VERSION @@ -1 +1 @@ -0.5.14.0222 Beta
\ No newline at end of file +0.5.14.0222 Beta diff --git a/templates/ng/base/footer.tmpl b/templates/ng/base/footer.tmpl index e152a4ded1..89836fca23 100644 --- a/templates/ng/base/footer.tmpl +++ b/templates/ng/base/footer.tmpl @@ -1,7 +1,7 @@ </div> <footer id="footer"> <div class="container clear"> - <p class="left" id="footer-rights">© 2015 GoGits · {{.i18n.Tr "version"}}: {{AppVer}} · {{.i18n.Tr "page"}}: <strong>{{LoadTimes .PageStartTime}}</strong> · + <p class="left" id="footer-rights">© 2015 Gogs · {{.i18n.Tr "version"}}: {{AppVer}} · {{.i18n.Tr "page"}}: <strong>{{LoadTimes .PageStartTime}}</strong> · {{.i18n.Tr "template"}}: <strong>{{call .TmplLoadTimes}}</strong></p> <div class="right" id="footer-links"> diff --git a/templates/org/home.tmpl b/templates/org/home.tmpl index df29d61fc4..fdce06a298 100644 --- a/templates/org/home.tmpl +++ b/templates/org/home.tmpl @@ -27,7 +27,7 @@ </div> <div id="org-repo-list"> {{range .Repos}} - {{if or (not .IsPrivate) (.HasAccess $.SignedUser.Name)}} + {{if or (not .IsPrivate) (.HasAccess $.SignedUser)}} <div class="org-repo-item"> <ul class="org-repo-status right"> <li><i class="octicon octicon-star"></i> {{.NumStars}}</li> diff --git a/templates/user/profile.tmpl b/templates/user/profile.tmpl index a18a8b50d6..dab90c35a2 100644 --- a/templates/user/profile.tmpl +++ b/templates/user/profile.tmpl @@ -74,7 +74,7 @@ <div class="tab-pane active"> <div id="org-repo-list"> {{range .Repos}} - {{if or (not .IsPrivate) (.HasAccess $.SignedUserName)}} + {{if or (not .IsPrivate) (.HasAccess $.SignedUser)}} <div class="org-repo-item"> <ul class="org-repo-status right"> <li><i class="octicon octicon-star"></i> {{.NumStars}}</li> |