You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

297 lines
8.4 KiB

  1. // Copyright 2016 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "fmt"
  7. "time"
  8. "code.gitea.io/gitea/modules/base"
  9. "code.gitea.io/gitea/modules/log"
  10. "code.gitea.io/gitea/modules/setting"
  11. "code.gitea.io/gitea/modules/util"
  12. "github.com/Unknwon/com"
  13. )
  14. const (
  15. // ProtectedBranchRepoID protected Repo ID
  16. ProtectedBranchRepoID = "GITEA_REPO_ID"
  17. )
  18. // ProtectedBranch struct
  19. type ProtectedBranch struct {
  20. ID int64 `xorm:"pk autoincr"`
  21. RepoID int64 `xorm:"UNIQUE(s)"`
  22. BranchName string `xorm:"UNIQUE(s)"`
  23. CanPush bool `xorm:"NOT NULL DEFAULT false"`
  24. EnableWhitelist bool
  25. WhitelistUserIDs []int64 `xorm:"JSON TEXT"`
  26. WhitelistTeamIDs []int64 `xorm:"JSON TEXT"`
  27. CreatedUnix util.TimeStamp `xorm:"created"`
  28. UpdatedUnix util.TimeStamp `xorm:"updated"`
  29. }
  30. // IsProtected returns if the branch is protected
  31. func (protectBranch *ProtectedBranch) IsProtected() bool {
  32. return protectBranch.ID > 0
  33. }
  34. // CanUserPush returns if some user could push to this protected branch
  35. func (protectBranch *ProtectedBranch) CanUserPush(userID int64) bool {
  36. if !protectBranch.EnableWhitelist {
  37. return false
  38. }
  39. if base.Int64sContains(protectBranch.WhitelistUserIDs, userID) {
  40. return true
  41. }
  42. if len(protectBranch.WhitelistTeamIDs) == 0 {
  43. return false
  44. }
  45. in, err := IsUserInTeams(userID, protectBranch.WhitelistTeamIDs)
  46. if err != nil {
  47. log.Error(1, "IsUserInTeams:", err)
  48. return false
  49. }
  50. return in
  51. }
  52. // GetProtectedBranchByRepoID getting protected branch by repo ID
  53. func GetProtectedBranchByRepoID(RepoID int64) ([]*ProtectedBranch, error) {
  54. protectedBranches := make([]*ProtectedBranch, 0)
  55. return protectedBranches, x.Where("repo_id = ?", RepoID).Desc("updated_unix").Find(&protectedBranches)
  56. }
  57. // GetProtectedBranchBy getting protected branch by ID/Name
  58. func GetProtectedBranchBy(repoID int64, BranchName string) (*ProtectedBranch, error) {
  59. rel := &ProtectedBranch{RepoID: repoID, BranchName: BranchName}
  60. has, err := x.Get(rel)
  61. if err != nil {
  62. return nil, err
  63. }
  64. if !has {
  65. return nil, nil
  66. }
  67. return rel, nil
  68. }
  69. // GetProtectedBranchByID getting protected branch by ID
  70. func GetProtectedBranchByID(id int64) (*ProtectedBranch, error) {
  71. rel := &ProtectedBranch{ID: id}
  72. has, err := x.Get(rel)
  73. if err != nil {
  74. return nil, err
  75. }
  76. if !has {
  77. return nil, nil
  78. }
  79. return rel, nil
  80. }
  81. // UpdateProtectBranch saves branch protection options of repository.
  82. // If ID is 0, it creates a new record. Otherwise, updates existing record.
  83. // This function also performs check if whitelist user and team's IDs have been changed
  84. // to avoid unnecessary whitelist delete and regenerate.
  85. func UpdateProtectBranch(repo *Repository, protectBranch *ProtectedBranch, whitelistUserIDs, whitelistTeamIDs []int64) (err error) {
  86. if err = repo.GetOwner(); err != nil {
  87. return fmt.Errorf("GetOwner: %v", err)
  88. }
  89. hasUsersChanged := !util.IsSliceInt64Eq(protectBranch.WhitelistUserIDs, whitelistUserIDs)
  90. if hasUsersChanged {
  91. protectBranch.WhitelistUserIDs = make([]int64, 0, len(whitelistUserIDs))
  92. for _, userID := range whitelistUserIDs {
  93. has, err := hasAccess(x, userID, repo, AccessModeWrite)
  94. if err != nil {
  95. return fmt.Errorf("HasAccess [user_id: %d, repo_id: %d]: %v", userID, protectBranch.RepoID, err)
  96. } else if !has {
  97. continue // Drop invalid user ID
  98. }
  99. protectBranch.WhitelistUserIDs = append(protectBranch.WhitelistUserIDs, userID)
  100. }
  101. }
  102. // if the repo is in an orgniziation
  103. hasTeamsChanged := !util.IsSliceInt64Eq(protectBranch.WhitelistTeamIDs, whitelistTeamIDs)
  104. if hasTeamsChanged {
  105. teams, err := GetTeamsWithAccessToRepo(repo.OwnerID, repo.ID, AccessModeWrite)
  106. if err != nil {
  107. return fmt.Errorf("GetTeamsWithAccessToRepo [org_id: %d, repo_id: %d]: %v", repo.OwnerID, repo.ID, err)
  108. }
  109. protectBranch.WhitelistTeamIDs = make([]int64, 0, len(teams))
  110. for i := range teams {
  111. if teams[i].HasWriteAccess() && com.IsSliceContainsInt64(whitelistTeamIDs, teams[i].ID) {
  112. protectBranch.WhitelistTeamIDs = append(protectBranch.WhitelistTeamIDs, teams[i].ID)
  113. }
  114. }
  115. }
  116. // Make sure protectBranch.ID is not 0 for whitelists
  117. if protectBranch.ID == 0 {
  118. if _, err = x.Insert(protectBranch); err != nil {
  119. return fmt.Errorf("Insert: %v", err)
  120. }
  121. return nil
  122. }
  123. if _, err = x.ID(protectBranch.ID).AllCols().Update(protectBranch); err != nil {
  124. return fmt.Errorf("Update: %v", err)
  125. }
  126. return nil
  127. }
  128. // GetProtectedBranches get all protected branches
  129. func (repo *Repository) GetProtectedBranches() ([]*ProtectedBranch, error) {
  130. protectedBranches := make([]*ProtectedBranch, 0)
  131. return protectedBranches, x.Find(&protectedBranches, &ProtectedBranch{RepoID: repo.ID})
  132. }
  133. // IsProtectedBranch checks if branch is protected
  134. func (repo *Repository) IsProtectedBranch(branchName string, doer *User) (bool, error) {
  135. if doer == nil {
  136. return true, nil
  137. }
  138. protectedBranch := &ProtectedBranch{
  139. RepoID: repo.ID,
  140. BranchName: branchName,
  141. }
  142. has, err := x.Get(protectedBranch)
  143. if err != nil {
  144. return true, err
  145. } else if has {
  146. return !protectedBranch.CanUserPush(doer.ID), nil
  147. }
  148. return false, nil
  149. }
  150. // DeleteProtectedBranch removes ProtectedBranch relation between the user and repository.
  151. func (repo *Repository) DeleteProtectedBranch(id int64) (err error) {
  152. protectedBranch := &ProtectedBranch{
  153. RepoID: repo.ID,
  154. ID: id,
  155. }
  156. sess := x.NewSession()
  157. defer sess.Close()
  158. if err = sess.Begin(); err != nil {
  159. return err
  160. }
  161. if affected, err := sess.Delete(protectedBranch); err != nil {
  162. return err
  163. } else if affected != 1 {
  164. return fmt.Errorf("delete protected branch ID(%v) failed", id)
  165. }
  166. return sess.Commit()
  167. }
  168. // DeletedBranch struct
  169. type DeletedBranch struct {
  170. ID int64 `xorm:"pk autoincr"`
  171. RepoID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  172. Name string `xorm:"UNIQUE(s) NOT NULL"`
  173. Commit string `xorm:"UNIQUE(s) NOT NULL"`
  174. DeletedByID int64 `xorm:"INDEX"`
  175. DeletedBy *User `xorm:"-"`
  176. DeletedUnix util.TimeStamp `xorm:"INDEX created"`
  177. }
  178. // AddDeletedBranch adds a deleted branch to the database
  179. func (repo *Repository) AddDeletedBranch(branchName, commit string, deletedByID int64) error {
  180. deletedBranch := &DeletedBranch{
  181. RepoID: repo.ID,
  182. Name: branchName,
  183. Commit: commit,
  184. DeletedByID: deletedByID,
  185. }
  186. sess := x.NewSession()
  187. defer sess.Close()
  188. if err := sess.Begin(); err != nil {
  189. return err
  190. }
  191. if _, err := sess.InsertOne(deletedBranch); err != nil {
  192. return err
  193. }
  194. return sess.Commit()
  195. }
  196. // GetDeletedBranches returns all the deleted branches
  197. func (repo *Repository) GetDeletedBranches() ([]*DeletedBranch, error) {
  198. deletedBranches := make([]*DeletedBranch, 0)
  199. return deletedBranches, x.Where("repo_id = ?", repo.ID).Desc("deleted_unix").Find(&deletedBranches)
  200. }
  201. // GetDeletedBranchByID get a deleted branch by its ID
  202. func (repo *Repository) GetDeletedBranchByID(ID int64) (*DeletedBranch, error) {
  203. deletedBranch := &DeletedBranch{ID: ID}
  204. has, err := x.Get(deletedBranch)
  205. if err != nil {
  206. return nil, err
  207. }
  208. if !has {
  209. return nil, nil
  210. }
  211. return deletedBranch, nil
  212. }
  213. // RemoveDeletedBranch removes a deleted branch from the database
  214. func (repo *Repository) RemoveDeletedBranch(id int64) (err error) {
  215. deletedBranch := &DeletedBranch{
  216. RepoID: repo.ID,
  217. ID: id,
  218. }
  219. sess := x.NewSession()
  220. defer sess.Close()
  221. if err = sess.Begin(); err != nil {
  222. return err
  223. }
  224. if affected, err := sess.Delete(deletedBranch); err != nil {
  225. return err
  226. } else if affected != 1 {
  227. return fmt.Errorf("remove deleted branch ID(%v) failed", id)
  228. }
  229. return sess.Commit()
  230. }
  231. // LoadUser loads the user that deleted the branch
  232. // When there's no user found it returns a NewGhostUser
  233. func (deletedBranch *DeletedBranch) LoadUser() {
  234. user, err := GetUserByID(deletedBranch.DeletedByID)
  235. if err != nil {
  236. user = NewGhostUser()
  237. }
  238. deletedBranch.DeletedBy = user
  239. }
  240. // RemoveOldDeletedBranches removes old deleted branches
  241. func RemoveOldDeletedBranches() {
  242. if !taskStatusTable.StartIfNotRunning(`deleted_branches_cleanup`) {
  243. return
  244. }
  245. defer taskStatusTable.Stop(`deleted_branches_cleanup`)
  246. log.Trace("Doing: DeletedBranchesCleanup")
  247. deleteBefore := time.Now().Add(-setting.Cron.DeletedBranchesCleanup.OlderThan)
  248. _, err := x.Where("deleted_unix < ?", deleteBefore.Unix()).Delete(new(DeletedBranch))
  249. if err != nil {
  250. log.Error(4, "DeletedBranchesCleanup: %v", err)
  251. }
  252. }