123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138 |
- package db
- import (
- "gorm.io/gorm"
- log "unknwon.dev/clog/v2"
- )
- type PermsStore interface {
-
- AccessMode(userID, repoID int64, opts AccessModeOptions) AccessMode
-
- Authorize(userID, repoID int64, desired AccessMode, opts AccessModeOptions) bool
-
-
- SetRepoPerms(repoID int64, accessMap map[int64]AccessMode) error
- }
- var Perms PermsStore
- type Access struct {
- ID int64
- UserID int64 `xorm:"UNIQUE(s)" gorm:"uniqueIndex:access_user_repo_unique;NOT NULL"`
- RepoID int64 `xorm:"UNIQUE(s)" gorm:"uniqueIndex:access_user_repo_unique;NOT NULL"`
- Mode AccessMode `gorm:"NOT NULL"`
- }
- type AccessMode int
- const (
- AccessModeNone AccessMode = iota
- AccessModeRead
- AccessModeWrite
- AccessModeAdmin
- AccessModeOwner
- )
- func (mode AccessMode) String() string {
- switch mode {
- case AccessModeRead:
- return "read"
- case AccessModeWrite:
- return "write"
- case AccessModeAdmin:
- return "admin"
- case AccessModeOwner:
- return "owner"
- default:
- return "none"
- }
- }
- func ParseAccessMode(permission string) AccessMode {
- switch permission {
- case "write":
- return AccessModeWrite
- case "admin":
- return AccessModeAdmin
- default:
- return AccessModeRead
- }
- }
- var _ PermsStore = (*perms)(nil)
- type perms struct {
- *gorm.DB
- }
- type AccessModeOptions struct {
- OwnerID int64
- Private bool
- }
- func (db *perms) AccessMode(userID, repoID int64, opts AccessModeOptions) (mode AccessMode) {
- if repoID <= 0 {
- return AccessModeNone
- }
-
- if !opts.Private {
- mode = AccessModeRead
- }
-
- if userID <= 0 {
- return mode
- }
- if userID == opts.OwnerID {
- return AccessModeOwner
- }
- access := new(Access)
- err := db.Where("user_id = ? AND repo_id = ?", userID, repoID).First(access).Error
- if err != nil {
- if err != gorm.ErrRecordNotFound {
- log.Error("Failed to get access [user_id: %d, repo_id: %d]: %v", userID, repoID, err)
- }
- return mode
- }
- return access.Mode
- }
- func (db *perms) Authorize(userID, repoID int64, desired AccessMode, opts AccessModeOptions) bool {
- return desired <= db.AccessMode(userID, repoID, opts)
- }
- func (db *perms) SetRepoPerms(repoID int64, accessMap map[int64]AccessMode) error {
- records := make([]*Access, 0, len(accessMap))
- for userID, mode := range accessMap {
- records = append(records, &Access{
- UserID: userID,
- RepoID: repoID,
- Mode: mode,
- })
- }
- return db.Transaction(func(tx *gorm.DB) error {
- err := tx.Where("repo_id = ?", repoID).Delete(new(Access)).Error
- if err != nil {
- return err
- }
- return tx.Create(&records).Error
- })
- }
|