Fork to maintain patches against the official gitea for https://code.ceondo.com https://github.com/go-gitea/gitea

user.go 35KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308
  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. "bytes"
  7. "container/list"
  8. "crypto/sha256"
  9. "crypto/subtle"
  10. "encoding/hex"
  11. "errors"
  12. "fmt"
  13. "image"
  14. // Needed for jpeg support
  15. _ "image/jpeg"
  16. "image/png"
  17. "os"
  18. "path/filepath"
  19. "strings"
  20. "time"
  21. "unicode/utf8"
  22. "github.com/Unknwon/com"
  23. "github.com/go-xorm/xorm"
  24. "github.com/nfnt/resize"
  25. "golang.org/x/crypto/pbkdf2"
  26. "code.gitea.io/git"
  27. api "code.gitea.io/sdk/gitea"
  28. "code.gitea.io/gitea/modules/avatar"
  29. "code.gitea.io/gitea/modules/base"
  30. "code.gitea.io/gitea/modules/log"
  31. "code.gitea.io/gitea/modules/markdown"
  32. "code.gitea.io/gitea/modules/setting"
  33. )
  34. // UserType defines the user type
  35. type UserType int
  36. const (
  37. // UserTypeIndividual defines an individual user
  38. UserTypeIndividual UserType = iota // Historic reason to make it starts at 0.
  39. // UserTypeOrganization defines an organization
  40. UserTypeOrganization
  41. )
  42. var (
  43. // ErrUserNotKeyOwner user does not own this key error
  44. ErrUserNotKeyOwner = errors.New("User does not own this public key")
  45. // ErrEmailNotExist e-mail does not exist error
  46. ErrEmailNotExist = errors.New("E-mail does not exist")
  47. // ErrEmailNotActivated e-mail address has not been activated error
  48. ErrEmailNotActivated = errors.New("E-mail address has not been activated")
  49. // ErrUserNameIllegal user name contains illegal characters error
  50. ErrUserNameIllegal = errors.New("User name contains illegal characters")
  51. // ErrLoginSourceNotActived login source is not actived error
  52. ErrLoginSourceNotActived = errors.New("Login source is not actived")
  53. // ErrUnsupportedLoginType login source is unknown error
  54. ErrUnsupportedLoginType = errors.New("Login source is unknown")
  55. )
  56. // User represents the object of individual and member of organization.
  57. type User struct {
  58. ID int64 `xorm:"pk autoincr"`
  59. LowerName string `xorm:"UNIQUE NOT NULL"`
  60. Name string `xorm:"UNIQUE NOT NULL"`
  61. FullName string
  62. // Email is the primary email address (to be used for communication)
  63. Email string `xorm:"NOT NULL"`
  64. KeepEmailPrivate bool
  65. Passwd string `xorm:"NOT NULL"`
  66. LoginType LoginType
  67. LoginSource int64 `xorm:"NOT NULL DEFAULT 0"`
  68. LoginName string
  69. Type UserType
  70. OwnedOrgs []*User `xorm:"-"`
  71. Orgs []*User `xorm:"-"`
  72. Repos []*Repository `xorm:"-"`
  73. Location string
  74. Website string
  75. Rands string `xorm:"VARCHAR(10)"`
  76. Salt string `xorm:"VARCHAR(10)"`
  77. Created time.Time `xorm:"-"`
  78. CreatedUnix int64 `xorm:"INDEX"`
  79. Updated time.Time `xorm:"-"`
  80. UpdatedUnix int64 `xorm:"INDEX"`
  81. LastLogin time.Time `xorm:"-"`
  82. LastLoginUnix int64 `xorm:"INDEX"`
  83. // Remember visibility choice for convenience, true for private
  84. LastRepoVisibility bool
  85. // Maximum repository creation limit, -1 means use global default
  86. MaxRepoCreation int `xorm:"NOT NULL DEFAULT -1"`
  87. // Permissions
  88. IsActive bool `xorm:"INDEX"` // Activate primary email
  89. IsAdmin bool
  90. AllowGitHook bool
  91. AllowImportLocal bool // Allow migrate repository by local path
  92. AllowCreateOrganization bool `xorm:"DEFAULT true"`
  93. ProhibitLogin bool
  94. // Avatar
  95. Avatar string `xorm:"VARCHAR(2048) NOT NULL"`
  96. AvatarEmail string `xorm:"NOT NULL"`
  97. UseCustomAvatar bool
  98. // Counters
  99. NumFollowers int
  100. NumFollowing int `xorm:"NOT NULL DEFAULT 0"`
  101. NumStars int
  102. NumRepos int
  103. // For organization
  104. Description string
  105. NumTeams int
  106. NumMembers int
  107. Teams []*Team `xorm:"-"`
  108. Members []*User `xorm:"-"`
  109. // Preferences
  110. DiffViewStyle string `xorm:"NOT NULL DEFAULT ''"`
  111. }
  112. // BeforeInsert is invoked from XORM before inserting an object of this type.
  113. func (u *User) BeforeInsert() {
  114. u.CreatedUnix = time.Now().Unix()
  115. u.UpdatedUnix = u.CreatedUnix
  116. }
  117. // BeforeUpdate is invoked from XORM before updating this object.
  118. func (u *User) BeforeUpdate() {
  119. if u.MaxRepoCreation < -1 {
  120. u.MaxRepoCreation = -1
  121. }
  122. u.UpdatedUnix = time.Now().Unix()
  123. }
  124. // SetLastLogin set time to last login
  125. func (u *User) SetLastLogin() {
  126. u.LastLoginUnix = time.Now().Unix()
  127. }
  128. // UpdateDiffViewStyle updates the users diff view style
  129. func (u *User) UpdateDiffViewStyle(style string) error {
  130. u.DiffViewStyle = style
  131. return UpdateUser(u)
  132. }
  133. // AfterSet is invoked from XORM after setting the value of a field of this object.
  134. func (u *User) AfterSet(colName string, _ xorm.Cell) {
  135. switch colName {
  136. case "full_name":
  137. u.FullName = markdown.Sanitizer.Sanitize(u.FullName)
  138. case "created_unix":
  139. u.Created = time.Unix(u.CreatedUnix, 0).Local()
  140. case "updated_unix":
  141. u.Updated = time.Unix(u.UpdatedUnix, 0).Local()
  142. case "last_login_unix":
  143. u.LastLogin = time.Unix(u.LastLoginUnix, 0).Local()
  144. }
  145. }
  146. // getEmail returns an noreply email, if the user has set to keep his
  147. // email address private, otherwise the primary email address.
  148. func (u *User) getEmail() string {
  149. if u.KeepEmailPrivate {
  150. return fmt.Sprintf("%s@%s", u.LowerName, setting.Service.NoReplyAddress)
  151. }
  152. return u.Email
  153. }
  154. // APIFormat converts a User to api.User
  155. func (u *User) APIFormat() *api.User {
  156. return &api.User{
  157. ID: u.ID,
  158. UserName: u.Name,
  159. FullName: u.FullName,
  160. Email: u.getEmail(),
  161. AvatarURL: u.AvatarLink(),
  162. }
  163. }
  164. // IsLocal returns true if user login type is LoginPlain.
  165. func (u *User) IsLocal() bool {
  166. return u.LoginType <= LoginPlain
  167. }
  168. // HasForkedRepo checks if user has already forked a repository with given ID.
  169. func (u *User) HasForkedRepo(repoID int64) bool {
  170. _, has := HasForkedRepo(u.ID, repoID)
  171. return has
  172. }
  173. // RepoCreationNum returns the number of repositories created by the user
  174. func (u *User) RepoCreationNum() int {
  175. if u.MaxRepoCreation <= -1 {
  176. return setting.Repository.MaxCreationLimit
  177. }
  178. return u.MaxRepoCreation
  179. }
  180. // CanCreateRepo returns if user login can create a repository
  181. func (u *User) CanCreateRepo() bool {
  182. if u.MaxRepoCreation <= -1 {
  183. if setting.Repository.MaxCreationLimit <= -1 {
  184. return true
  185. }
  186. return u.NumRepos < setting.Repository.MaxCreationLimit
  187. }
  188. return u.NumRepos < u.MaxRepoCreation
  189. }
  190. // CanCreateOrganization returns true if user can create organisation.
  191. func (u *User) CanCreateOrganization() bool {
  192. return u.IsAdmin || u.AllowCreateOrganization
  193. }
  194. // CanEditGitHook returns true if user can edit Git hooks.
  195. func (u *User) CanEditGitHook() bool {
  196. return u.IsAdmin || u.AllowGitHook
  197. }
  198. // CanImportLocal returns true if user can migrate repository by local path.
  199. func (u *User) CanImportLocal() bool {
  200. if !setting.ImportLocalPaths {
  201. return false
  202. }
  203. return u.IsAdmin || u.AllowImportLocal
  204. }
  205. // DashboardLink returns the user dashboard page link.
  206. func (u *User) DashboardLink() string {
  207. if u.IsOrganization() {
  208. return setting.AppSubURL + "/org/" + u.Name + "/dashboard/"
  209. }
  210. return setting.AppSubURL + "/"
  211. }
  212. // HomeLink returns the user or organization home page link.
  213. func (u *User) HomeLink() string {
  214. return setting.AppSubURL + "/" + u.Name
  215. }
  216. // GenerateEmailActivateCode generates an activate code based on user information and given e-mail.
  217. func (u *User) GenerateEmailActivateCode(email string) string {
  218. code := base.CreateTimeLimitCode(
  219. com.ToStr(u.ID)+email+u.LowerName+u.Passwd+u.Rands,
  220. setting.Service.ActiveCodeLives, nil)
  221. // Add tail hex username
  222. code += hex.EncodeToString([]byte(u.LowerName))
  223. return code
  224. }
  225. // GenerateActivateCode generates an activate code based on user information.
  226. func (u *User) GenerateActivateCode() string {
  227. return u.GenerateEmailActivateCode(u.Email)
  228. }
  229. // CustomAvatarPath returns user custom avatar file path.
  230. func (u *User) CustomAvatarPath() string {
  231. return filepath.Join(setting.AvatarUploadPath, com.ToStr(u.ID))
  232. }
  233. // GenerateRandomAvatar generates a random avatar for user.
  234. func (u *User) GenerateRandomAvatar() error {
  235. seed := u.Email
  236. if len(seed) == 0 {
  237. seed = u.Name
  238. }
  239. img, err := avatar.RandomImage([]byte(seed))
  240. if err != nil {
  241. return fmt.Errorf("RandomImage: %v", err)
  242. }
  243. if err = os.MkdirAll(filepath.Dir(u.CustomAvatarPath()), os.ModePerm); err != nil {
  244. return fmt.Errorf("MkdirAll: %v", err)
  245. }
  246. fw, err := os.Create(u.CustomAvatarPath())
  247. if err != nil {
  248. return fmt.Errorf("Create: %v", err)
  249. }
  250. defer fw.Close()
  251. if err = png.Encode(fw, img); err != nil {
  252. return fmt.Errorf("Encode: %v", err)
  253. }
  254. log.Info("New random avatar created: %d", u.ID)
  255. return nil
  256. }
  257. // RelAvatarLink returns relative avatar link to the site domain,
  258. // which includes app sub-url as prefix. However, it is possible
  259. // to return full URL if user enables Gravatar-like service.
  260. func (u *User) RelAvatarLink() string {
  261. defaultImgURL := setting.AppSubURL + "/img/avatar_default.png"
  262. if u.ID == -1 {
  263. return defaultImgURL
  264. }
  265. switch {
  266. case u.UseCustomAvatar:
  267. if !com.IsExist(u.CustomAvatarPath()) {
  268. return defaultImgURL
  269. }
  270. return setting.AppSubURL + "/avatars/" + com.ToStr(u.ID)
  271. case setting.DisableGravatar, setting.OfflineMode:
  272. if !com.IsExist(u.CustomAvatarPath()) {
  273. if err := u.GenerateRandomAvatar(); err != nil {
  274. log.Error(3, "GenerateRandomAvatar: %v", err)
  275. }
  276. }
  277. return setting.AppSubURL + "/avatars/" + com.ToStr(u.ID)
  278. }
  279. return base.AvatarLink(u.AvatarEmail)
  280. }
  281. // AvatarLink returns user avatar absolute link.
  282. func (u *User) AvatarLink() string {
  283. link := u.RelAvatarLink()
  284. if link[0] == '/' && link[1] != '/' {
  285. return setting.AppURL + strings.TrimPrefix(link, setting.AppSubURL)[1:]
  286. }
  287. return link
  288. }
  289. // GetFollowers returns range of user's followers.
  290. func (u *User) GetFollowers(page int) ([]*User, error) {
  291. users := make([]*User, 0, ItemsPerPage)
  292. sess := x.
  293. Limit(ItemsPerPage, (page-1)*ItemsPerPage).
  294. Where("follow.follow_id=?", u.ID)
  295. if setting.UsePostgreSQL {
  296. sess = sess.Join("LEFT", "follow", `"user".id=follow.user_id`)
  297. } else {
  298. sess = sess.Join("LEFT", "follow", "user.id=follow.user_id")
  299. }
  300. return users, sess.Find(&users)
  301. }
  302. // IsFollowing returns true if user is following followID.
  303. func (u *User) IsFollowing(followID int64) bool {
  304. return IsFollowing(u.ID, followID)
  305. }
  306. // GetFollowing returns range of user's following.
  307. func (u *User) GetFollowing(page int) ([]*User, error) {
  308. users := make([]*User, 0, ItemsPerPage)
  309. sess := x.
  310. Limit(ItemsPerPage, (page-1)*ItemsPerPage).
  311. Where("follow.user_id=?", u.ID)
  312. if setting.UsePostgreSQL {
  313. sess = sess.Join("LEFT", "follow", `"user".id=follow.follow_id`)
  314. } else {
  315. sess = sess.Join("LEFT", "follow", "user.id=follow.follow_id")
  316. }
  317. return users, sess.Find(&users)
  318. }
  319. // NewGitSig generates and returns the signature of given user.
  320. func (u *User) NewGitSig() *git.Signature {
  321. return &git.Signature{
  322. Name: u.DisplayName(),
  323. Email: u.getEmail(),
  324. When: time.Now(),
  325. }
  326. }
  327. // EncodePasswd encodes password to safe format.
  328. func (u *User) EncodePasswd() {
  329. newPasswd := pbkdf2.Key([]byte(u.Passwd), []byte(u.Salt), 10000, 50, sha256.New)
  330. u.Passwd = fmt.Sprintf("%x", newPasswd)
  331. }
  332. // ValidatePassword checks if given password matches the one belongs to the user.
  333. func (u *User) ValidatePassword(passwd string) bool {
  334. newUser := &User{Passwd: passwd, Salt: u.Salt}
  335. newUser.EncodePasswd()
  336. return subtle.ConstantTimeCompare([]byte(u.Passwd), []byte(newUser.Passwd)) == 1
  337. }
  338. // UploadAvatar saves custom avatar for user.
  339. // FIXME: split uploads to different subdirs in case we have massive users.
  340. func (u *User) UploadAvatar(data []byte) error {
  341. img, _, err := image.Decode(bytes.NewReader(data))
  342. if err != nil {
  343. return fmt.Errorf("Decode: %v", err)
  344. }
  345. m := resize.Resize(avatar.AvatarSize, avatar.AvatarSize, img, resize.NearestNeighbor)
  346. sess := x.NewSession()
  347. defer sessionRelease(sess)
  348. if err = sess.Begin(); err != nil {
  349. return err
  350. }
  351. u.UseCustomAvatar = true
  352. if err = updateUser(sess, u); err != nil {
  353. return fmt.Errorf("updateUser: %v", err)
  354. }
  355. if err := os.MkdirAll(setting.AvatarUploadPath, os.ModePerm); err != nil {
  356. return fmt.Errorf("Failed to create dir %s: %v", setting.AvatarUploadPath, err)
  357. }
  358. fw, err := os.Create(u.CustomAvatarPath())
  359. if err != nil {
  360. return fmt.Errorf("Create: %v", err)
  361. }
  362. defer fw.Close()
  363. if err = png.Encode(fw, m); err != nil {
  364. return fmt.Errorf("Encode: %v", err)
  365. }
  366. return sess.Commit()
  367. }
  368. // DeleteAvatar deletes the user's custom avatar.
  369. func (u *User) DeleteAvatar() error {
  370. log.Trace("DeleteAvatar[%d]: %s", u.ID, u.CustomAvatarPath())
  371. if err := os.Remove(u.CustomAvatarPath()); err != nil {
  372. return fmt.Errorf("Failed to remove %s: %v", u.CustomAvatarPath(), err)
  373. }
  374. u.UseCustomAvatar = false
  375. if err := UpdateUser(u); err != nil {
  376. return fmt.Errorf("UpdateUser: %v", err)
  377. }
  378. return nil
  379. }
  380. // IsAdminOfRepo returns true if user has admin or higher access of repository.
  381. func (u *User) IsAdminOfRepo(repo *Repository) bool {
  382. has, err := HasAccess(u, repo, AccessModeAdmin)
  383. if err != nil {
  384. log.Error(3, "HasAccess: %v", err)
  385. }
  386. return has
  387. }
  388. // IsWriterOfRepo returns true if user has write access to given repository.
  389. func (u *User) IsWriterOfRepo(repo *Repository) bool {
  390. has, err := HasAccess(u, repo, AccessModeWrite)
  391. if err != nil {
  392. log.Error(3, "HasAccess: %v", err)
  393. }
  394. return has
  395. }
  396. // IsOrganization returns true if user is actually a organization.
  397. func (u *User) IsOrganization() bool {
  398. return u.Type == UserTypeOrganization
  399. }
  400. // IsUserOrgOwner returns true if user is in the owner team of given organization.
  401. func (u *User) IsUserOrgOwner(orgID int64) bool {
  402. return IsOrganizationOwner(orgID, u.ID)
  403. }
  404. // IsPublicMember returns true if user public his/her membership in given organization.
  405. func (u *User) IsPublicMember(orgID int64) bool {
  406. return IsPublicMembership(orgID, u.ID)
  407. }
  408. func (u *User) getOrganizationCount(e Engine) (int64, error) {
  409. return e.
  410. Where("uid=?", u.ID).
  411. Count(new(OrgUser))
  412. }
  413. // GetOrganizationCount returns count of membership of organization of user.
  414. func (u *User) GetOrganizationCount() (int64, error) {
  415. return u.getOrganizationCount(x)
  416. }
  417. // GetRepositories returns repositories that user owns, including private repositories.
  418. func (u *User) GetRepositories(page, pageSize int) (err error) {
  419. u.Repos, err = GetUserRepositories(u.ID, true, page, pageSize)
  420. return err
  421. }
  422. // GetMirrorRepositories returns mirror repositories that user owns, including private repositories.
  423. func (u *User) GetMirrorRepositories() ([]*Repository, error) {
  424. return GetUserMirrorRepositories(u.ID)
  425. }
  426. // GetOwnedOrganizations returns all organizations that user owns.
  427. func (u *User) GetOwnedOrganizations() (err error) {
  428. u.OwnedOrgs, err = GetOwnedOrgsByUserID(u.ID)
  429. return err
  430. }
  431. // GetOrganizations returns all organizations that user belongs to.
  432. func (u *User) GetOrganizations(all bool) error {
  433. ous, err := GetOrgUsersByUserID(u.ID, all)
  434. if err != nil {
  435. return err
  436. }
  437. u.Orgs = make([]*User, len(ous))
  438. for i, ou := range ous {
  439. u.Orgs[i], err = GetUserByID(ou.OrgID)
  440. if err != nil {
  441. return err
  442. }
  443. }
  444. return nil
  445. }
  446. // DisplayName returns full name if it's not empty,
  447. // returns username otherwise.
  448. func (u *User) DisplayName() string {
  449. if len(u.FullName) > 0 {
  450. return u.FullName
  451. }
  452. return u.Name
  453. }
  454. // ShortName ellipses username to length
  455. func (u *User) ShortName(length int) string {
  456. return base.EllipsisString(u.Name, length)
  457. }
  458. // IsMailable checks if a user is elegible
  459. // to receive emails.
  460. func (u *User) IsMailable() bool {
  461. return u.IsActive
  462. }
  463. // IsUserExist checks if given user name exist,
  464. // the user name should be noncased unique.
  465. // If uid is presented, then check will rule out that one,
  466. // it is used when update a user name in settings page.
  467. func IsUserExist(uid int64, name string) (bool, error) {
  468. if len(name) == 0 {
  469. return false, nil
  470. }
  471. return x.
  472. Where("id!=?", uid).
  473. Get(&User{LowerName: strings.ToLower(name)})
  474. }
  475. // GetUserSalt returns a ramdom user salt token.
  476. func GetUserSalt() (string, error) {
  477. return base.GetRandomString(10)
  478. }
  479. // NewGhostUser creates and returns a fake user for someone has deleted his/her account.
  480. func NewGhostUser() *User {
  481. return &User{
  482. ID: -1,
  483. Name: "Ghost",
  484. LowerName: "ghost",
  485. }
  486. }
  487. var (
  488. reservedUsernames = []string{"assets", "css", "img", "js", "less", "plugins", "debug", "raw", "install", "api", "avatar", "user", "org", "help", "stars", "issues", "pulls", "commits", "repo", "template", "admin", "new", ".", ".."}
  489. reservedUserPatterns = []string{"*.keys"}
  490. )
  491. // isUsableName checks if name is reserved or pattern of name is not allowed
  492. // based on given reserved names and patterns.
  493. // Names are exact match, patterns can be prefix or suffix match with placeholder '*'.
  494. func isUsableName(names, patterns []string, name string) error {
  495. name = strings.TrimSpace(strings.ToLower(name))
  496. if utf8.RuneCountInString(name) == 0 {
  497. return ErrNameEmpty
  498. }
  499. for i := range names {
  500. if name == names[i] {
  501. return ErrNameReserved{name}
  502. }
  503. }
  504. for _, pat := range patterns {
  505. if pat[0] == '*' && strings.HasSuffix(name, pat[1:]) ||
  506. (pat[len(pat)-1] == '*' && strings.HasPrefix(name, pat[:len(pat)-1])) {
  507. return ErrNamePatternNotAllowed{pat}
  508. }
  509. }
  510. return nil
  511. }
  512. // IsUsableUsername returns an error when a username is reserved
  513. func IsUsableUsername(name string) error {
  514. return isUsableName(reservedUsernames, reservedUserPatterns, name)
  515. }
  516. // CreateUser creates record of a new user.
  517. func CreateUser(u *User) (err error) {
  518. if err = IsUsableUsername(u.Name); err != nil {
  519. return err
  520. }
  521. isExist, err := IsUserExist(0, u.Name)
  522. if err != nil {
  523. return err
  524. } else if isExist {
  525. return ErrUserAlreadyExist{u.Name}
  526. }
  527. u.Email = strings.ToLower(u.Email)
  528. has, err := x.
  529. Where("email=?", u.Email).
  530. Get(new(User))
  531. if err != nil {
  532. return err
  533. } else if has {
  534. return ErrEmailAlreadyUsed{u.Email}
  535. }
  536. isExist, err = IsEmailUsed(u.Email)
  537. if err != nil {
  538. return err
  539. } else if isExist {
  540. return ErrEmailAlreadyUsed{u.Email}
  541. }
  542. u.KeepEmailPrivate = setting.Service.DefaultKeepEmailPrivate
  543. u.LowerName = strings.ToLower(u.Name)
  544. u.AvatarEmail = u.Email
  545. u.Avatar = base.HashEmail(u.AvatarEmail)
  546. if u.Rands, err = GetUserSalt(); err != nil {
  547. return err
  548. }
  549. if u.Salt, err = GetUserSalt(); err != nil {
  550. return err
  551. }
  552. u.EncodePasswd()
  553. u.AllowCreateOrganization = true
  554. u.MaxRepoCreation = -1
  555. sess := x.NewSession()
  556. defer sessionRelease(sess)
  557. if err = sess.Begin(); err != nil {
  558. return err
  559. }
  560. if _, err = sess.Insert(u); err != nil {
  561. return err
  562. } else if err = os.MkdirAll(UserPath(u.Name), os.ModePerm); err != nil {
  563. return err
  564. }
  565. return sess.Commit()
  566. }
  567. func countUsers(e Engine) int64 {
  568. count, _ := e.
  569. Where("type=0").
  570. Count(new(User))
  571. return count
  572. }
  573. // CountUsers returns number of users.
  574. func CountUsers() int64 {
  575. return countUsers(x)
  576. }
  577. // Users returns number of users in given page.
  578. func Users(opts *SearchUserOptions) ([]*User, error) {
  579. if len(opts.OrderBy) == 0 {
  580. opts.OrderBy = "name ASC"
  581. }
  582. users := make([]*User, 0, opts.PageSize)
  583. sess := x.
  584. Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).
  585. Where("type=0")
  586. return users, sess.
  587. OrderBy(opts.OrderBy).
  588. Find(&users)
  589. }
  590. // get user by verify code
  591. func getVerifyUser(code string) (user *User) {
  592. if len(code) <= base.TimeLimitCodeLength {
  593. return nil
  594. }
  595. // use tail hex username query user
  596. hexStr := code[base.TimeLimitCodeLength:]
  597. if b, err := hex.DecodeString(hexStr); err == nil {
  598. if user, err = GetUserByName(string(b)); user != nil {
  599. return user
  600. }
  601. log.Error(4, "user.getVerifyUser: %v", err)
  602. }
  603. return nil
  604. }
  605. // VerifyUserActiveCode verifies active code when active account
  606. func VerifyUserActiveCode(code string) (user *User) {
  607. minutes := setting.Service.ActiveCodeLives
  608. if user = getVerifyUser(code); user != nil {
  609. // time limit code
  610. prefix := code[:base.TimeLimitCodeLength]
  611. data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Passwd + user.Rands
  612. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  613. return user
  614. }
  615. }
  616. return nil
  617. }
  618. // VerifyActiveEmailCode verifies active email code when active account
  619. func VerifyActiveEmailCode(code, email string) *EmailAddress {
  620. minutes := setting.Service.ActiveCodeLives
  621. if user := getVerifyUser(code); user != nil {
  622. // time limit code
  623. prefix := code[:base.TimeLimitCodeLength]
  624. data := com.ToStr(user.ID) + email + user.LowerName + user.Passwd + user.Rands
  625. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  626. emailAddress := &EmailAddress{Email: email}
  627. if has, _ := x.Get(emailAddress); has {
  628. return emailAddress
  629. }
  630. }
  631. }
  632. return nil
  633. }
  634. // ChangeUserName changes all corresponding setting from old user name to new one.
  635. func ChangeUserName(u *User, newUserName string) (err error) {
  636. if err = IsUsableUsername(newUserName); err != nil {
  637. return err
  638. }
  639. isExist, err := IsUserExist(0, newUserName)
  640. if err != nil {
  641. return err
  642. } else if isExist {
  643. return ErrUserAlreadyExist{newUserName}
  644. }
  645. if err = ChangeUsernameInPullRequests(u.Name, newUserName); err != nil {
  646. return fmt.Errorf("ChangeUsernameInPullRequests: %v", err)
  647. }
  648. // Delete all local copies of repository wiki that user owns.
  649. if err = x.
  650. Where("owner_id=?", u.ID).
  651. Iterate(new(Repository), func(idx int, bean interface{}) error {
  652. repo := bean.(*Repository)
  653. RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
  654. return nil
  655. }); err != nil {
  656. return fmt.Errorf("Delete repository wiki local copy: %v", err)
  657. }
  658. return os.Rename(UserPath(u.Name), UserPath(newUserName))
  659. }
  660. func updateUser(e Engine, u *User) error {
  661. // Organization does not need email
  662. if !u.IsOrganization() {
  663. u.Email = strings.ToLower(u.Email)
  664. has, err := e.
  665. Where("id!=?", u.ID).
  666. And("type=?", u.Type).
  667. And("email=?", u.Email).
  668. Get(new(User))
  669. if err != nil {
  670. return err
  671. } else if has {
  672. return ErrEmailAlreadyUsed{u.Email}
  673. }
  674. if len(u.AvatarEmail) == 0 {
  675. u.AvatarEmail = u.Email
  676. }
  677. u.Avatar = base.HashEmail(u.AvatarEmail)
  678. }
  679. u.LowerName = strings.ToLower(u.Name)
  680. u.Location = base.TruncateString(u.Location, 255)
  681. u.Website = base.TruncateString(u.Website, 255)
  682. u.Description = base.TruncateString(u.Description, 255)
  683. u.FullName = markdown.Sanitizer.Sanitize(u.FullName)
  684. _, err := e.Id(u.ID).AllCols().Update(u)
  685. return err
  686. }
  687. // UpdateUser updates user's information.
  688. func UpdateUser(u *User) error {
  689. return updateUser(x, u)
  690. }
  691. // deleteBeans deletes all given beans, beans should contain delete conditions.
  692. func deleteBeans(e Engine, beans ...interface{}) (err error) {
  693. for i := range beans {
  694. if _, err = e.Delete(beans[i]); err != nil {
  695. return err
  696. }
  697. }
  698. return nil
  699. }
  700. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  701. func deleteUser(e *xorm.Session, u *User) error {
  702. // Note: A user owns any repository or belongs to any organization
  703. // cannot perform delete operation.
  704. // Check ownership of repository.
  705. count, err := getRepositoryCount(e, u)
  706. if err != nil {
  707. return fmt.Errorf("GetRepositoryCount: %v", err)
  708. } else if count > 0 {
  709. return ErrUserOwnRepos{UID: u.ID}
  710. }
  711. // Check membership of organization.
  712. count, err = u.getOrganizationCount(e)
  713. if err != nil {
  714. return fmt.Errorf("GetOrganizationCount: %v", err)
  715. } else if count > 0 {
  716. return ErrUserHasOrgs{UID: u.ID}
  717. }
  718. // ***** START: Watch *****
  719. watches := make([]*Watch, 0, 10)
  720. if err = e.Find(&watches, &Watch{UserID: u.ID}); err != nil {
  721. return fmt.Errorf("get all watches: %v", err)
  722. }
  723. for i := range watches {
  724. if _, err = e.Exec("UPDATE `repository` SET num_watches=num_watches-1 WHERE id=?", watches[i].RepoID); err != nil {
  725. return fmt.Errorf("decrease repository watch number[%d]: %v", watches[i].RepoID, err)
  726. }
  727. }
  728. // ***** END: Watch *****
  729. // ***** START: Star *****
  730. stars := make([]*Star, 0, 10)
  731. if err = e.Find(&stars, &Star{UID: u.ID}); err != nil {
  732. return fmt.Errorf("get all stars: %v", err)
  733. }
  734. for i := range stars {
  735. if _, err = e.Exec("UPDATE `repository` SET num_stars=num_stars-1 WHERE id=?", stars[i].RepoID); err != nil {
  736. return fmt.Errorf("decrease repository star number[%d]: %v", stars[i].RepoID, err)
  737. }
  738. }
  739. // ***** END: Star *****
  740. // ***** START: Follow *****
  741. followers := make([]*Follow, 0, 10)
  742. if err = e.Find(&followers, &Follow{UserID: u.ID}); err != nil {
  743. return fmt.Errorf("get all followers: %v", err)
  744. }
  745. for i := range followers {
  746. if _, err = e.Exec("UPDATE `user` SET num_followers=num_followers-1 WHERE id=?", followers[i].UserID); err != nil {
  747. return fmt.Errorf("decrease user follower number[%d]: %v", followers[i].UserID, err)
  748. }
  749. }
  750. // ***** END: Follow *****
  751. if err = deleteBeans(e,
  752. &AccessToken{UID: u.ID},
  753. &Collaboration{UserID: u.ID},
  754. &Access{UserID: u.ID},
  755. &Watch{UserID: u.ID},
  756. &Star{UID: u.ID},
  757. &Follow{FollowID: u.ID},
  758. &Action{UserID: u.ID},
  759. &IssueUser{UID: u.ID},
  760. &EmailAddress{UID: u.ID},
  761. ); err != nil {
  762. return fmt.Errorf("deleteBeans: %v", err)
  763. }
  764. // ***** START: PublicKey *****
  765. keys := make([]*PublicKey, 0, 10)
  766. if err = e.Find(&keys, &PublicKey{OwnerID: u.ID}); err != nil {
  767. return fmt.Errorf("get all public keys: %v", err)
  768. }
  769. keyIDs := make([]int64, len(keys))
  770. for i := range keys {
  771. keyIDs[i] = keys[i].ID
  772. }
  773. if err = deletePublicKeys(e, keyIDs...); err != nil {
  774. return fmt.Errorf("deletePublicKeys: %v", err)
  775. }
  776. // ***** END: PublicKey *****
  777. // Clear assignee.
  778. if _, err = e.Exec("UPDATE `issue` SET assignee_id=0 WHERE assignee_id=?", u.ID); err != nil {
  779. return fmt.Errorf("clear assignee: %v", err)
  780. }
  781. if _, err = e.Id(u.ID).Delete(new(User)); err != nil {
  782. return fmt.Errorf("Delete: %v", err)
  783. }
  784. // FIXME: system notice
  785. // Note: There are something just cannot be roll back,
  786. // so just keep error logs of those operations.
  787. path := UserPath(u.Name)
  788. if err := os.RemoveAll(path); err != nil {
  789. return fmt.Errorf("Failed to RemoveAll %s: %v", path, err)
  790. }
  791. avatarPath := u.CustomAvatarPath()
  792. if com.IsExist(avatarPath) {
  793. if err := os.Remove(avatarPath); err != nil {
  794. return fmt.Errorf("Failed to remove %s: %v", avatarPath, err)
  795. }
  796. }
  797. return nil
  798. }
  799. // DeleteUser completely and permanently deletes everything of a user,
  800. // but issues/comments/pulls will be kept and shown as someone has been deleted.
  801. func DeleteUser(u *User) (err error) {
  802. sess := x.NewSession()
  803. defer sessionRelease(sess)
  804. if err = sess.Begin(); err != nil {
  805. return err
  806. }
  807. if err = deleteUser(sess, u); err != nil {
  808. // Note: don't wrapper error here.
  809. return err
  810. }
  811. if err = sess.Commit(); err != nil {
  812. return err
  813. }
  814. return RewriteAllPublicKeys()
  815. }
  816. // DeleteInactivateUsers deletes all inactivate users and email addresses.
  817. func DeleteInactivateUsers() (err error) {
  818. users := make([]*User, 0, 10)
  819. if err = x.
  820. Where("is_active = ?", false).
  821. Find(&users); err != nil {
  822. return fmt.Errorf("get all inactive users: %v", err)
  823. }
  824. // FIXME: should only update authorized_keys file once after all deletions.
  825. for _, u := range users {
  826. if err = DeleteUser(u); err != nil {
  827. // Ignore users that were set inactive by admin.
  828. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  829. continue
  830. }
  831. return err
  832. }
  833. }
  834. _, err = x.
  835. Where("is_activated = ?", false).
  836. Delete(new(EmailAddress))
  837. return err
  838. }
  839. // UserPath returns the path absolute path of user repositories.
  840. func UserPath(userName string) string {
  841. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  842. }
  843. // GetUserByKeyID get user information by user's public key id
  844. func GetUserByKeyID(keyID int64) (*User, error) {
  845. var user User
  846. has, err := x.Join("INNER", "public_key", "`public_key`.owner_id = `user`.id").
  847. Where("`public_key`.id=?", keyID).
  848. Get(&user)
  849. if err != nil {
  850. return nil, err
  851. }
  852. if !has {
  853. return nil, ErrUserNotExist{0, "", keyID}
  854. }
  855. return &user, nil
  856. }
  857. func getUserByID(e Engine, id int64) (*User, error) {
  858. u := new(User)
  859. has, err := e.Id(id).Get(u)
  860. if err != nil {
  861. return nil, err
  862. } else if !has {
  863. return nil, ErrUserNotExist{id, "", 0}
  864. }
  865. return u, nil
  866. }
  867. // GetUserByID returns the user object by given ID if exists.
  868. func GetUserByID(id int64) (*User, error) {
  869. return getUserByID(x, id)
  870. }
  871. // GetAssigneeByID returns the user with write access of repository by given ID.
  872. func GetAssigneeByID(repo *Repository, userID int64) (*User, error) {
  873. has, err := HasAccess(&User{ID: userID}, repo, AccessModeWrite)
  874. if err != nil {
  875. return nil, err
  876. } else if !has {
  877. return nil, ErrUserNotExist{userID, "", 0}
  878. }
  879. return GetUserByID(userID)
  880. }
  881. // GetUserByName returns user by given name.
  882. func GetUserByName(name string) (*User, error) {
  883. if len(name) == 0 {
  884. return nil, ErrUserNotExist{0, name, 0}
  885. }
  886. u := &User{LowerName: strings.ToLower(name)}
  887. has, err := x.Get(u)
  888. if err != nil {
  889. return nil, err
  890. } else if !has {
  891. return nil, ErrUserNotExist{0, name, 0}
  892. }
  893. return u, nil
  894. }
  895. // GetUserEmailsByNames returns a list of e-mails corresponds to names.
  896. func GetUserEmailsByNames(names []string) []string {
  897. mails := make([]string, 0, len(names))
  898. for _, name := range names {
  899. u, err := GetUserByName(name)
  900. if err != nil {
  901. continue
  902. }
  903. if u.IsMailable() {
  904. mails = append(mails, u.Email)
  905. }
  906. }
  907. return mails
  908. }
  909. // GetUsersByIDs returns all resolved users from a list of Ids.
  910. func GetUsersByIDs(ids []int64) ([]*User, error) {
  911. ous := make([]*User, 0, len(ids))
  912. if len(ids) == 0 {
  913. return ous, nil
  914. }
  915. err := x.In("id", ids).
  916. Asc("name").
  917. Find(&ous)
  918. return ous, err
  919. }
  920. // GetUserIDsByNames returns a slice of ids corresponds to names.
  921. func GetUserIDsByNames(names []string) []int64 {
  922. ids := make([]int64, 0, len(names))
  923. for _, name := range names {
  924. u, err := GetUserByName(name)
  925. if err != nil {
  926. continue
  927. }
  928. ids = append(ids, u.ID)
  929. }
  930. return ids
  931. }
  932. // UserCommit represents a commit with validation of user.
  933. type UserCommit struct {
  934. User *User
  935. *git.Commit
  936. }
  937. // ValidateCommitWithEmail check if author's e-mail of commit is corresponding to a user.
  938. func ValidateCommitWithEmail(c *git.Commit) *User {
  939. u, err := GetUserByEmail(c.Author.Email)
  940. if err != nil {
  941. return nil
  942. }
  943. return u
  944. }
  945. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  946. func ValidateCommitsWithEmails(oldCommits *list.List) *list.List {
  947. var (
  948. u *User
  949. emails = map[string]*User{}
  950. newCommits = list.New()
  951. e = oldCommits.Front()
  952. )
  953. for e != nil {
  954. c := e.Value.(*git.Commit)
  955. if v, ok := emails[c.Author.Email]; !ok {
  956. u, _ = GetUserByEmail(c.Author.Email)
  957. emails[c.Author.Email] = u
  958. } else {
  959. u = v
  960. }
  961. newCommits.PushBack(UserCommit{
  962. User: u,
  963. Commit: c,
  964. })
  965. e = e.Next()
  966. }
  967. return newCommits
  968. }
  969. // GetUserByEmail returns the user object by given e-mail if exists.
  970. func GetUserByEmail(email string) (*User, error) {
  971. if len(email) == 0 {
  972. return nil, ErrUserNotExist{0, email, 0}
  973. }
  974. email = strings.ToLower(email)
  975. // First try to find the user by primary email
  976. user := &User{Email: email}
  977. has, err := x.Get(user)
  978. if err != nil {
  979. return nil, err
  980. }
  981. if has {
  982. return user, nil
  983. }
  984. // Otherwise, check in alternative list for activated email addresses
  985. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  986. has, err = x.Get(emailAddress)
  987. if err != nil {
  988. return nil, err
  989. }
  990. if has {
  991. return GetUserByID(emailAddress.UID)
  992. }
  993. return nil, ErrUserNotExist{0, email, 0}
  994. }
  995. // SearchUserOptions contains the options for searching
  996. type SearchUserOptions struct {
  997. Keyword string
  998. Type UserType
  999. OrderBy string
  1000. Page int
  1001. PageSize int // Can be smaller than or equal to setting.UI.ExplorePagingNum
  1002. }
  1003. // SearchUserByName takes keyword and part of user name to search,
  1004. // it returns results in given range and number of total results.
  1005. func SearchUserByName(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  1006. if len(opts.Keyword) == 0 {
  1007. return users, 0, nil
  1008. }
  1009. opts.Keyword = strings.ToLower(opts.Keyword)
  1010. if opts.PageSize <= 0 || opts.PageSize > setting.UI.ExplorePagingNum {
  1011. opts.PageSize = setting.UI.ExplorePagingNum
  1012. }
  1013. if opts.Page <= 0 {
  1014. opts.Page = 1
  1015. }
  1016. searchQuery := "%" + opts.Keyword + "%"
  1017. users = make([]*User, 0, opts.PageSize)
  1018. // Append conditions
  1019. sess := x.
  1020. Where("LOWER(lower_name) LIKE ?", searchQuery).
  1021. Or("LOWER(full_name) LIKE ?", searchQuery).
  1022. And("type = ?", opts.Type)
  1023. var countSess xorm.Session
  1024. countSess = *sess
  1025. count, err := countSess.Count(new(User))
  1026. if err != nil {
  1027. return nil, 0, fmt.Errorf("Count: %v", err)
  1028. }
  1029. if len(opts.OrderBy) > 0 {
  1030. sess.OrderBy(opts.OrderBy)
  1031. }
  1032. return users, count, sess.
  1033. Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).
  1034. Find(&users)
  1035. }
  1036. // ___________ .__ .__
  1037. // \_ _____/___ | | | | ______ _ __
  1038. // | __)/ _ \| | | | / _ \ \/ \/ /
  1039. // | \( <_> ) |_| |_( <_> ) /
  1040. // \___ / \____/|____/____/\____/ \/\_/
  1041. // \/
  1042. // Follow represents relations of user and his/her followers.
  1043. type Follow struct {
  1044. ID int64 `xorm:"pk autoincr"`
  1045. UserID int64 `xorm:"UNIQUE(follow)"`
  1046. FollowID int64 `xorm:"UNIQUE(follow)"`
  1047. }
  1048. // IsFollowing returns true if user is following followID.
  1049. func IsFollowing(userID, followID int64) bool {
  1050. has, _ := x.Get(&Follow{UserID: userID, FollowID: followID})
  1051. return has
  1052. }
  1053. // FollowUser marks someone be another's follower.
  1054. func FollowUser(userID, followID int64) (err error) {
  1055. if userID == followID || IsFollowing(userID, followID) {
  1056. return nil
  1057. }
  1058. sess := x.NewSession()
  1059. defer sessionRelease(sess)
  1060. if err = sess.Begin(); err != nil {
  1061. return err
  1062. }
  1063. if _, err = sess.Insert(&Follow{UserID: userID, FollowID: followID}); err != nil {
  1064. return err
  1065. }
  1066. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?", followID); err != nil {
  1067. return err
  1068. }
  1069. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following + 1 WHERE id = ?", userID); err != nil {
  1070. return err
  1071. }
  1072. return sess.Commit()
  1073. }
  1074. // UnfollowUser unmarks someone as another's follower.
  1075. func UnfollowUser(userID, followID int64) (err error) {
  1076. if userID == followID || !IsFollowing(userID, followID) {
  1077. return nil
  1078. }
  1079. sess := x.NewSession()
  1080. defer sessionRelease(sess)
  1081. if err = sess.Begin(); err != nil {
  1082. return err
  1083. }
  1084. if _, err = sess.Delete(&Follow{UserID: userID, FollowID: followID}); err != nil {
  1085. return err
  1086. }
  1087. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?", followID); err != nil {
  1088. return err
  1089. }
  1090. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following - 1 WHERE id = ?", userID); err != nil {
  1091. return err
  1092. }
  1093. return sess.Commit()
  1094. }
  1095. // GetStarredRepos returns the repos starred by a particular user
  1096. func GetStarredRepos(userID int64, private bool) ([]*Repository, error) {
  1097. sess := x.Where("star.uid=?", userID).
  1098. Join("LEFT", "star", "`repository`.id=`star`.repo_id")
  1099. if !private {
  1100. sess = sess.And("is_private=?", false)
  1101. }
  1102. repos := make([]*Repository, 0, 10)
  1103. err := sess.Find(&repos)
  1104. if err != nil {
  1105. return nil, err
  1106. }
  1107. return repos, nil
  1108. }
  1109. // GetWatchedRepos returns the repos watched by a particular user
  1110. func GetWatchedRepos(userID int64, private bool) ([]*Repository, error) {
  1111. sess := x.Where("watch.user_id=?", userID).
  1112. Join("LEFT", "watch", "`repository`.id=`watch`.repo_id")
  1113. if !private {
  1114. sess = sess.And("is_private=?", false)
  1115. }
  1116. repos := make([]*Repository, 0, 10)
  1117. err := sess.Find(&repos)
  1118. if err != nil {
  1119. return nil, err
  1120. }
  1121. return repos, nil
  1122. }