perms.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Copyright 2020 The Gogs 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 db
  5. import (
  6. "github.com/jinzhu/gorm"
  7. log "unknwon.dev/clog/v2"
  8. )
  9. // PermsStore is the persistent interface for permissions.
  10. //
  11. // NOTE: All methods are sorted in alphabetical order.
  12. type PermsStore interface {
  13. // AccessMode returns the access mode of given user has to the repository.
  14. AccessMode(userID int64, repo *Repository) AccessMode
  15. // Authorize returns true if the user has as good as desired access mode to
  16. // the repository.
  17. Authorize(userID int64, repo *Repository, desired AccessMode) bool
  18. }
  19. var Perms PermsStore
  20. type perms struct {
  21. *gorm.DB
  22. }
  23. func (db *perms) AccessMode(userID int64, repo *Repository) AccessMode {
  24. var mode AccessMode
  25. // Everyone has read access to public repository.
  26. if !repo.IsPrivate {
  27. mode = AccessModeRead
  28. }
  29. // Quick check to avoid a DB query.
  30. if userID <= 0 {
  31. return mode
  32. }
  33. if userID == repo.OwnerID {
  34. return AccessModeOwner
  35. }
  36. access := new(Access)
  37. err := db.Where("user_id = ? AND repo_id = ?", userID, repo.ID).First(access).Error
  38. if err != nil {
  39. log.Error("Failed to get access [user_id: %d, repo_id: %d]: %v", userID, repo.ID, err)
  40. return mode
  41. }
  42. return access.Mode
  43. }
  44. func (db *perms) Authorize(userID int64, repo *Repository, desired AccessMode) bool {
  45. return desired <= db.AccessMode(userID, repo)
  46. }