access.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright 2014 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 models
  5. import (
  6. "strings"
  7. "time"
  8. "github.com/go-xorm/xorm"
  9. )
  10. type AccessType int
  11. const (
  12. READABLE AccessType = iota + 1
  13. WRITABLE
  14. )
  15. // Access represents the accessibility of user to repository.
  16. type Access struct {
  17. Id int64
  18. UserName string `xorm:"UNIQUE(s)"`
  19. RepoName string `xorm:"UNIQUE(s)"` // <user name>/<repo name>
  20. Mode AccessType `xorm:"UNIQUE(s)"`
  21. Created time.Time `xorm:"CREATED"`
  22. }
  23. // AddAccess adds new access record.
  24. func AddAccess(access *Access) error {
  25. access.UserName = strings.ToLower(access.UserName)
  26. access.RepoName = strings.ToLower(access.RepoName)
  27. _, err := x.Insert(access)
  28. return err
  29. }
  30. // UpdateAccess updates access information.
  31. func UpdateAccess(access *Access) error {
  32. access.UserName = strings.ToLower(access.UserName)
  33. access.RepoName = strings.ToLower(access.RepoName)
  34. _, err := x.Id(access.Id).Update(access)
  35. return err
  36. }
  37. // DeleteAccess deletes access record.
  38. func DeleteAccess(access *Access) error {
  39. _, err := x.Delete(access)
  40. return err
  41. }
  42. // UpdateAccess updates access information with session for rolling back.
  43. func UpdateAccessWithSession(sess *xorm.Session, access *Access) error {
  44. if _, err := sess.Id(access.Id).Update(access); err != nil {
  45. sess.Rollback()
  46. return err
  47. }
  48. return nil
  49. }
  50. // HasAccess returns true if someone can read or write to given repository.
  51. // The repoName should be in format <username>/<reponame>.
  52. func HasAccess(uname, repoName string, mode AccessType) (bool, error) {
  53. if len(repoName) == 0 {
  54. return false, nil
  55. }
  56. access := &Access{
  57. UserName: strings.ToLower(uname),
  58. RepoName: strings.ToLower(repoName),
  59. }
  60. has, err := x.Get(access)
  61. if err != nil {
  62. return false, err
  63. } else if !has {
  64. return false, nil
  65. } else if mode > access.Mode {
  66. return false, nil
  67. }
  68. return true, nil
  69. }